Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple columns to a data.table, where column names are held in a vector

Tags:

r

data.table

I want to add a large number of columns to a data.table in R. The column names are held in a vector a. How to do it?

x <- data.table(a=1,b=1)
f <- function(x) {list(0)}

The following works:

x <- x[, c("col1","col2","col3") := f()]

but the following doesn't:

a <- c("col1","col2","col3")
x <- x[, a := f()]

How do I add the columns defined within a?

like image 226
Tony Wolff Avatar asked Sep 19 '15 08:09

Tony Wolff


1 Answers

In order to make that work, you have to wrap the a in () like this:

x[, (a) := f()]

this results in the following datatable:

> x
   a b col1 col2 col3
1: 1 1    0    0    0

Explanation: when you use x[, a:=f()] you assign the outcome of f() to column a (data.table allows this for convenience). Thus a is treated as a name in this occasion. When you use (a), a is treated as an expression (in this case a vector of column names).

Furthermore: you don't need to assign this to x again with x <- as the datatable is updated by reference because the := operator is used.

like image 94
Jaap Avatar answered Sep 19 '22 04:09

Jaap