23

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]]
}
user1701545
  • 5,706
  • 14
  • 49
  • 80
  • 1
    I don't understand what you're trying to do. Are you sure you mean [data.table](http://datatable.r-forge.r-project.org/)? – Frank Sep 28 '13 at 21:54
  • This is just a toy example of a bigger problem that I really have. I have a tabular data structure object (with many fields) from which I want to copy several fields to a data.table. – user1701545 Sep 28 '13 at 22:00

2 Answers2

45

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]]
Matt Dowle
  • 58,872
  • 22
  • 166
  • 224
Kevin Ushey
  • 20,530
  • 5
  • 56
  • 88
  • Interestingly, it seems you can add columns simultaneously. For eg., `t = data.table(c1=1,c2=2); x = list(); x[1] <- 10; x[2] <- 100; invisible(foreach (i=1:2) %dopar% { input = x[[i]]; col = LETTERS[i]; t[ ,eval(col):= input] })` – xbsd Sep 29 '13 at 01:21
4

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
Jack Ryan
  • 2,134
  • 18
  • 26