Tony Wolff
Tony Wolff

Reputation: 742

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

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?

Upvotes: 6

Views: 2150

Answers (1)

Jaap
Jaap

Reputation: 83215

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.

Upvotes: 11

Related Questions