Suppose I have the following data.table
DT <- data.table(x = 1:5, y = 6:10, z = 11:15)
and I have a variable a <- "y"
. I could access the values of y
using DT[, get(a)]
, no problem.
However, if I try to set the values of y
to 0 using DT[, get(a) := 0]
, I get the following error:
Error in get(a) : object 'y' not found
Why can't get(a)
find y
when using :=
? How else could I update y
without referencing it directly? This is useful if a
is the argument of a function or I am iterating over a vector of variable names.
Answer: Well, it looks like DT[, (a) := 0]
, DT[, eval(a) := 0]
, DT[, c(a) := 0]
all answer this question. Thanks to @eddi and @AnandaMahto for their help in the comments.
The best explanation of this issue is on this thread: Removing multiple columns from r data table...