繁体   English   中英

将多列合并为一个列表列

[英]Combine multiple columns to one list column

我想在 R 中的 data.table 中将多个列组合到一个列表列中。示例:

require(data.table)

dt = data.table(col1 = LETTERS[1:5],
                col2 = rep('test', 5),
                col3 = c('hello', 'yes', 'no', 'maybe', 'why'))

问:如何将col2col3组合成一个列表列?

到目前为止我尝试过的:

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

您可以使用data.tabletranspose功能。

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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