Assigning sets of columns whose names are stored in a character vector is well discussed, but I can't seem to find a solution to retrieve columns and operate on them.
cols = c("x", "y")
DT = data.table(x = 10:15, y = 20:25)
> DT
x y
1: 10 20
2: 11 21
3: 12 22
4: 13 23
5: 14 24
6: 15 25
Desired Output
> DT[,paste(x,y)]
[1] "10 20" "11 21" "12 22" "13 23" "14 24" "15 25"
My goal is to get a unique identifier for each row based on the columns in cols. I can do this by hard coding the column names but I'd rather reference cols
Here are some syntax I have tried and their output.
get()
> DT[,get(cols)]
[1] 10 11 12 13 14 15
Parentheses
> DT[,(cols)]
[1] "x" "y"
List
> DT[,as.list(cols)]
V1 V2
1: x y
with=F
> DT[,cols, with=F]
x y
1: 10 20
2: 11 21
3: 12 22
4: 13 23
5: 14 24
6: 15 25
This works but I am unable to operate on the columns:
> DT[,paste(cols), with=F]
x y
1: 10 20
2: 11 21
3: 12 22
4: 13 23
5: 14 24
6: 15 25
paste(cols)is the same ascols, and in the latest version of data.table,with=FALSEisn't necessary in some of these cases.