gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:06:35 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com