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

如何在R语言数据框中轻松计算两组列的两两乘积

解决方案

你可以通过生成attribute1和attribute2的所有列名组合,再逐个计算乘积列并添加到原数据框中,具体代码如下:

library(dplyr)
library(purrr)

# 生成所有列名配对
attr_pairs <- expand.grid(attr1 = attribute1, attr2 = attribute2, stringsAsFactors = FALSE)

# 批量添加乘积列
df <- df %>%
  mutate(
    !!!set_names(
      map2(attr_pairs$attr1, attr_pairs$attr2, ~ .data[[.x]] * .data[[.y]]),
      paste(attr_pairs$attr1, attr_pairs$attr2, sep = "x")
    )
  )

原代码不符合预期的原因

你嵌套使用across的写法会导致内层across(attribute2)返回一个多列的数据框,外层across(attribute1)的每个迭代会把单个列和这个多列数据框相乘,最终得到的是每个attribute1列对应一组乘积列,但这些列会被打包成类似列表列的结构,而不是单独的32个列,因此无法得到你想要的结果。

另一种简洁写法(结合tidyr):

library(dplyr)
library(tidyr)

crossing(attr1 = attribute1, attr2 = attribute2) %>%
  mutate(
    new_col = paste(attr1, attr2, sep = "x"),
    calc_expr = map2(attr1, attr2, ~ quo(.data[[!!.x]] * .data[[!!.y]]))
  ) %>%
  pull(calc_expr, name = new_col) %>%
  {df %>% mutate(!!!.)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:35:01