3

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
1
  • Fyi, paste(cols) is the same as cols, and in the latest version of data.table, with=FALSE isn't necessary in some of these cases. Commented Dec 14, 2016 at 18:02

1 Answer 1

5

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))]
Sign up to request clarification or add additional context in comments.

1 Comment

This was a very illustrative answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.