Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference `data.table` column by name

Tags:

r

data.table

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]
like image 993
Daniel Krizian Avatar asked May 31 '14 18:05

Daniel Krizian


1 Answers

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
like image 90
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 24 '22 23:10

A5C1D2H2I1M1N2O1R2T1