Suppose there is:
DT = data.table(a=1, b=2, "a+b"=8)
and there is variable col="a+b"
referencing the third column of DT
How to perform an operation on that column by reference? Let's say I want multiply col
by 2
, so in the above example the result should be 8*2=16
, not (1+2)*2=6
For example, this obviously doesn't work:
DT[, c:=as.name(col)*2]
It sounds like you're looking for get
:
DT = data.table(a=1, b=2, "a+b"=8)
col = "a+b"
DT[, get(col) * 2]
# [1] 16
DT[, c := get(col) * 2]
DT
# a b a+b c
# 1: 1 2 8 16
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With