Reputation: 3973
I would like to combine multiple columns to one list column in a data.table in R. Example:
require(data.table)
dt = data.table(col1 = LETTERS[1:5],
col2 = rep('test', 5),
col3 = c('hello', 'yes', 'no', 'maybe', 'why'))
Q: How can I combine col2
and col3
into a list column?
What I've tried so far:
cols = c('col2', 'col3')
dt[ , col4 := paste0(.SD, collapse = ', '), .SDcols = cols,
by = 1:nrow(dt) ] # paste's them together
dt[ , col4 := c(.SD), .SDcols = cols,
by = 1:nrow(dt) ] # drops col3
dt[ , col4 := lapply(.SD, c), .SDcols = cols,
by = 1:nrow(dt) ] # drops col3
Upvotes: 2
Views: 385
Reputation: 887118
We can use
dt[, col4 := do.call(paste, c(.SD, sep = ", ")), .SDcols = col2:col3]
Upvotes: 2
Reputation: 388982
You can use data.table
's transpose
function.
library(data.table)
cols = c('col2', 'col3')
dt[ , col4 := lapply(transpose(.SD), c), .SDcols = cols]
dt
# col1 col2 col3 col4
#1: A test hello test,hello
#2: B test yes test,yes
#3: C test no test,no
#4: D test maybe test,maybe
#5: E test why test,why
class(dt$col4)
#[1] "list"
Upvotes: 3