简体   繁体   中英

Combine multiple columns to one list column

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

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"

我们可以用

dt[, col4 := do.call(paste, c(.SD, sep = ", ")), .SDcols = col2:col3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM