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

如何将R语言data.frame的指定列与每一列合并?附示例

问题:如何将指定列(T列)与数据框中其他列合并,得到宽格式结果?

我有如下数据框(实际数据规模更大):

df = data.frame(ID = c(1,2,2,3,4,5,5),
                T = c(1,1,2,1,2,1,2),
                product_1 = c('A','A','B','C','A','C','D'),
                product_2 = c('C','A','B','A','B','E','C')
)

希望得到如下输出结果:

ID product_1_T1 product_1_T2 product_2_T1 product_2_T2
1  1            A         <NA>            C         <NA>
2  2            A            B            A            B
3  3            C         <NA>            A         <NA>
4  4         <NA>            A         <NA>            B
5  5            C            D            E            C

解决方案

方法一:tidyverse pivot_wider(代码简洁易读,推荐)

用tidyverse套件中的pivot_wider可以快速实现长格式转宽格式,语法直观:

library(tidyverse)

df_wide <- df %>%
  pivot_wider(
    id_cols = ID,          # 按ID分组
    names_from = T,        # 用T列的取值生成新列名后缀
    values_from = c(product_1, product_2),  # 需要展开的目标列
    names_sep = "_"        # 列名拼接的分隔符
  )

print(df_wide)

方法二:data.table dcast(大数据量首选,效率更高)

如果你的数据规模很大,data.table的dcast运算速度远快于基础方法,适合处理海量数据:

library(data.table)

setDT(df)
df_wide <- dcast(df, ID ~ T, value.var = c("product_1", "product_2"), sep = "_")

# 调整列顺序以匹配期望输出
setcolorder(df_wide, c("ID", "product_1_1", "product_1_2", "product_2_1", "product_2_2"))
print(df_wide)

方法三:基础R reshape函数(无需额外安装包)

不想安装第三方包的话,直接用基础R的reshape函数也能实现:

df_wide <- reshape(
  df,
  idvar = "ID",
  timevar = "T",
  direction = "wide",
  sep = "_"
)

print(df_wide)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:33:21