6

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?

smci
  • 32,567
  • 20
  • 113
  • 146
Tony Wolff
  • 732
  • 1
  • 10
  • 23

1 Answers1

11

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.

Jaap
  • 81,064
  • 34
  • 182
  • 193