1
library(data.table)
irisDT = as.data.table(iris)

I am looking for this:

irisDT[, NewCol:= Sepal.Length]

but then programmatically, so with var = "Sepal.Length".

I would expect something like this:

var = "Sepal.Length"
irisDT[, NewCol := eval(var)]

This

var = "Sepal.Length"
irisDT$NewCol = irisDT[[var]] 

works, but irisDT is copied internally, which is undesirable.

Any help is welcome:-)

Martijn Tennekes
  • 1,833
  • 12
  • 16

1 Answers1

1

Would this be an option for you?

irisDT[, NewCol := get(..var)]

You can use get(var) as long there is no variable in your data.table that is called var so programmatically using ..var is safer (see also here).

TimTeaFan
  • 11,990
  • 2
  • 14
  • 32