如何将data.table与向量cbind:新增零值列并以向量元素为列名
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:
- Create a new data.table where each column is filled with 0, using
DT2for names:zero_columns <- data.table(lapply(DT2, function(col) rep(0, nrow(DT)))) - 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

