1

I want to assign values to a data.table column, but I need to use a variable to represent the column name. I actually want to assign multiple values to specific rows, but my problem is using the variable. Using get() doesn't work.

var1 <- "Ozone"
airq<-as.data.table(airquality)
fillwith <- as.data.table(data.frame(res=sample(1:100,37,replace=T)))
airq[is.na(get(var1)),get(var1):=fillwith[,res]] # doesn't work

>Error in get(var1) : object 'Ozone' not found

airq[is.na(get(var1)),Ozone:=fillwith[,res]] # works

With=FALSE won't of course work for assignment by reference.

Thank you in advance.

Ozeuss
  • 229
  • 1
  • 6
  • 3
    You don't need `get` on the LHS of assignment, just need parentheses: `airq[is.na(get(var1)), (var1) := fillwith[,res]]`. I'm sure this is covered somewhere on the help page. – eddi Jun 26 '15 at 19:22
  • 1
    This is also similar: http://stackoverflow.com/q/15790743/1191259 The answers to both are way longer than they need to be, though...probably somewhat out-of-date. – Frank Jun 26 '15 at 19:27
  • @eddi since the question, apparently, isn't getting closed as a dupe, you may as well make an actual answer despite the shortness. – Dean MacGregor Jun 28 '15 at 19:23

0 Answers0