将列添加到数据表

时间:2022-01-31 18:47:55

I have a data.frame (or a matrix or any other tabular data structure object for that matter):

我有一个data.frame(或矩阵或任何其他表格数据结构对象):

df = data.frame(field1 = c(1,1,1),field2 = c(2,2,2),field3 = c(3,3,3))

And I want to copy part of its columns - given in the vector below:

我想复制其部分列 - 在下面的向量中给出:

fields = c("field1","field2")

to a new data.table that already has 1 or more columns:

到已有1列或更多列的新data.table:

dt = data.table(fieldX = c("x","x","x"))

I'm looking for something more efficient (and elegant) than:

我正在寻找比以下更有效(和优雅)的东西:

for(f in 1:length(fields))
{
dt[,fields[f]] = df[,fields[f]]
}

2 个解决方案

#1


17  

You can use cbind:

你可以使用cbind:

cbind(dt, df[fields])

However, the most efficient way is still probably going to be to use data.table's assign by reference:

但是,最有效的方法仍然可能是使用data.table通过引用分配:

dt[, (fields) := df[fields]]

#2


2  

I think you want cbind

我想你想要cbind

cbind(dt, df[, 1:2])
# fieldX field1 field2
# 1      x      1      2
# 2      x      1      2
# 3      x      1      2

#1


17  

You can use cbind:

你可以使用cbind:

cbind(dt, df[fields])

However, the most efficient way is still probably going to be to use data.table's assign by reference:

但是,最有效的方法仍然可能是使用data.table通过引用分配:

dt[, (fields) := df[fields]]

#2


2  

I think you want cbind

我想你想要cbind

cbind(dt, df[, 1:2])
# fieldX field1 field2
# 1      x      1      2
# 2      x      1      2
# 3      x      1      2