簡體   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