[英]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:我想在 R 中的 data.table 中将多个列组合到一个列表列中。示例:
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?问:如何将col2
和col3
组合成一个列表列?
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.您可以使用data.table
的transpose
功能。
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.