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

如何按列索引合并data.table中第4列至末列的值

在data.table中通过列索引生成合并列

需求说明

需要在data.table中新增名为combinations的列,将第4列到最后一列的每行值用逗号分隔后存储。该代码需适配列数可变的data.table:起始列固定为第4列,但末列索引无法预先确定。已知按列名合并的方法可行,希望通过列索引实现。

已知可行的列名实现方式

mycols <- c("apple", "orange", "banana")
data[, combinations := paste(mycols, sep = ", ")]

尝试过的无效索引代码

ncols <- ncol(data)
my_cols <- data[, c(4:ncols)] 
data[, combinations := paste(mycols, sep = ", ")]

示例数据

library(data.table)
# 构造示例data.table
data <- fread("id  number  day apple  orange  banana  
1   35      2   red    orange  yellow
2   12      3   red    NA      yellow
3   47      5   NA     orange  yellow")

期望结果

idnumberdayappleorangebananacombinations
1352redorangeyellowred, orange, yellow
2123redNAyellowred, NA, yellow
3475NAorangeyellowNA, orange, yellow

正确的列索引实现方案

利用data.table的.SD(数据子集)和.SDcols参数指定目标列范围,结合do.call按行合并列值:

# 生成combinations列
data[, combinations := do.call(paste, c(.SD, sep = ", ")), .SDcols = 4:ncol(data)]

代码解释

  • .SDcols = 4:ncol(data):自动适配列数变化,明确指定处理第4列到最后一列
  • .SD:代表.SDcols选定的列子集
  • do.call(paste, c(.SD, sep = ", ")):将paste按行应用到列子集的每个元素上,实现每行的多值合并

之前的无效代码问题在于:提取列子集后直接用paste,会把整个列集合作为参数合并,而非按行处理每行的列值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:45:29