r - 将多列合并为一个列表列

标签 r data.table

我想将 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"

关于r - 将多列合并为一个列表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68363480/

相关文章:

r - 如何将 here() 用于 css、before_body 和 after_body 的路径?

rollapply 函数应用于列表中数据帧的特定列

r - 以编程方式将不同的函数应用于 data.table R 中的不同列

r - 轻松检查目标是否记录在其他变量中?

r - 基于 2 列的组值

r - 如何从数据子集中随机抽取并在 R 中引导统计测试

r - 按总体平均值划分 data.table 行

r - 在 R 中的 ggplot2 中操作数据点的值

R 中使用 fread 的 data.table 的行限制

r - 提高 xts 的多个时间范围子集的性能?