3

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...

Community
  • 1
  • 1
  • I suspect it's because `get(a)` inside a `data.table` operator returns something different than an object. I've not used `data.table` so this may not be correct. – Carl Witthoft Jul 08 '14 at 16:52
  • 2
    this is almost certainly a duplicate - the correct syntax for what you want is `DT[, (a) := 0]` – eddi Jul 08 '14 at 17:06
  • @eddi, is there much of a difference between what you wrote and `eval(a)` (which I was about to suggest but didn't because I'm posting from my phone right now). – A5C1D2H2I1M1N2O1R2T1 Jul 08 '14 at 17:11
  • @AnandaMahto the difference is typing an extra `eval` and also *doing* an extra `eval` internally (pretty unimportant as far as performance goes) – eddi Jul 08 '14 at 17:28
  • Thanks @eddi and Ananda, both your suggestions work. I understand this is a very basic question but I couldn't find it elsewhere. I'll post the answer and reference your comments. – Diego Gruber Jul 08 '14 at 17:36
  • 2
    Also here : http://stackoverflow.com/a/24590543/403310 – Matt Dowle Jul 08 '14 at 18:54

0 Answers0