You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用purrr::map2为数据框添加x*与y*对应乘积的新列

解决方案

方法1:基础for循环(简单直接)

直接遍历下标,逐个计算并添加新列,新手友好:

df <- data.frame(x1 = 1:3,
                 x2 = 2:4,
                 x3 = 3:5,
                 y1 = 1:3,
                 y2 = 2:4,
                 y3 = 3:5)

for(i in 1:3){
  df[[paste0("result", i)]] <- df[[paste0("x", i)]] * df[[paste0("y", i)]]
}

方法2:tidyverse + purrr 风格实现

用reduce累积添加列,或者提取x/y列对后批量计算:

方式A:reduce循环添加

library(tidyverse)

df <- df %>%
  reduce(1:3, .init = ., function(.df, i){
    .df %>% mutate(!!sym(paste0("result", i)) := !!sym(paste0("x", i)) * !!sym(paste0("y", i)))
  })

方式B:提取列对批量计算后合并

x_cols <- df %>% select(starts_with("x"))
y_cols <- df %>% select(starts_with("y"))

# 计算乘积并命名结果列
results <- imap_dfc(x_cols, ~ .x * y_cols[[.y]]) %>%
  rename_with(~ str_replace(., "x", "result"))

df <- bind_cols(df, results)

方法3:用across实现简洁配对计算

利用列名规律,通过循环下标一次性生成所有结果列:

df <- df %>%
  mutate(across(1:3, 
                ~ .data[[paste0("x", .x)]] * .data[[paste0("y", .x)]],
                .names = "result{.x}"))

内容的提问来源于stack exchange,提问作者deschen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:40:32