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

如何将data.table与向量cbind:新增零值列并以向量元素为列名

Adding Zero-Valued Columns to a data.table Using a Vector for Column Names

Got it, let's tackle this problem—you're absolutely right that plain cbind(DT, DT2) only adds the vector as a single column, which isn't what you need. Here's how to properly create those zero-filled columns with your desired names:

Quickest & Most Efficient Method (Using data.table's := Operator)

If you're working with data.table, the := assignment operator is the way to go—it's fast and clean, especially for large datasets. You can add all the new columns in one line:

# Add columns directly to the original DT (modifies in place)
DT[, (DT2) := 0]

If you don't want to alter the original data.table, make a copy first:

DT_combined <- copy(DT)
DT_combined[, (DT2) := 0]

The parentheses around DT2 are crucial here—they tell data.table to use the values of DT2 as column names, not the literal string "DT2".

Step-by-Step Breakdown (For Clarity)

If you prefer to see the process explicitly, here's how to build the zero-valued columns separately first:

  1. Create a new data.table where each column is filled with 0, using DT2 for names:
    zero_columns <- data.table(lapply(DT2, function(col) rep(0, nrow(DT))))
    
  2. Combine this with your original data.table using cbind():
    DT_combined <- cbind(DT, zero_columns)
    

Full Working Example

Let's test this with your sample data:

library(data.table)

# Original data.table
DT <- data.table(x=c("A", "B", "C", "D", "E", "F"), y = rnorm(6))
# Vector of new column names
DT2 <- c("paper11grid1", "paper12grid1", "paper13grid1")

# Using the := method (in-place modification)
DT[, (DT2) := 0]

# Check the result
print(DT)

This will give you the original x and y columns, plus three new columns named after DT2 where every value is 0.

Why Your Original Approach Failed

When you use cbind(DT, DT2), R treats the vector DT2 as a single column (it'll even name it DT2 by default!) instead of recognizing that you want those values to be column names. The methods above explicitly map the vector values to column names and fill each with zeros, which fixes that issue.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:18:21