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

如何为R语言数据框的每行高效添加含多值的新列?

高效实现数据框行扩展的方法

方法1:tidyverse工具(简洁推荐)

利用dplyr的行分组结合tidyr::expand_grid,直接让原数据每行与新列组合做笛卡尔积,代码简洁高效:

library(tidyverse)

# 原数据框
df <- data.frame(
  col1 = c(1,2,3),
  col2 = c('A','F','Z'),
  col3 = c('R', 'E', 'P')
)

# 生成目标数据框
df2 <- df %>%
  rowwise() %>%
  expand_grid(
    col4 = c('Total', 'Average'),
    col5 = c('ZZ', 'BB')
  ) %>%
  ungroup()

方法2:Base R 原生实现

无需加载第三方包,通过expand.grid生成新列组合,再结合rep重复原数据行后拼接:

# 原数据框
df <- data.frame(
  col1 = c(1,2,3),
  col2 = c('A','F','Z'),
  col3 = c('R', 'E', 'P')
)

# 创建新列的所有组合
new_cols <- expand.grid(col4 = c('Total', 'Average'), col5 = c('ZZ', 'BB'), stringsAsFactors = FALSE)
# 重复原数据行并拼接新列
df2 <- cbind(df[rep(seq(nrow(df)), each = nrow(new_cols)), ], new_cols[rep(seq(nrow(new_cols)), nrow(df)), ])

方法3:data.table(大数据场景首选)

针对超大数据集,data.table的分组扩展性能更出色:

library(data.table)

# 原数据框转为data.table
df <- data.frame(
  col1 = c(1,2,3),
  col2 = c('A','F','Z'),
  col3 = c('R', 'E', 'P')
)
setDT(df)

# 生成目标数据框
df2 <- df[, .(col4 = c('Total', 'Average'), col5 = c('ZZ', 'BB')), by = .(col1, col2, col3)]

以上三种方法都能替代“复制两次再合并”的冗余操作,其中tidyverse方法最易读,data.table方法在大数据下效率最高,Base R方法无需额外依赖,可根据需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:40:24