user1701545
user1701545

Reputation: 6200

Adding columns to a data table

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

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:

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]]
}

Upvotes: 24

Views: 103484

Answers (2)

Kevin Ushey
Kevin Ushey

Reputation: 21285

You can use cbind:

cbind(dt, df[fields])

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

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

Upvotes: 46

Jack Ryan
Jack Ryan

Reputation: 2144

I think you want cbind

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

Upvotes: 4

Related Questions