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
We can use paste with do.call on the Subset of Data.table (.SD)
DT[, do.call(paste, .SD)]
#[1] "10 20" "11 21" "12 22" "13 23" "14 24" "15 25"
If this needs to be done on a subset of columns, specify those columns in .SDcols and then do the above
DT[, do.call(paste, .SD), .SDcols = cols]
#[1] "10 20" "11 21" "12 22" "13 23" "14 24" "15 25"
Or use a modification of OP's solution with mget
DT[, do.call(paste, mget(cols))]
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