Daniel Krizian Daniel Krizian - 3 months ago 18
R Question

Reference `data.table` column by name

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]

Answer

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