gpt4 book ai didi

r - data.table 按索引粘贴选定的列

转载 作者:行者123 更新时间:2023-12-04 07:37:12 25 4
gpt4 key购买 nike

我有一个 data.table 如下

DT <- structure(list(V1 = structure(1:3, .Label = c("S01", "S02", "S03"), class = "factor"), V2 = structure(c(1L, 3L, 2L), .Label = c("Alan", "Bruce", "Jay"), class = "factor"), V3 = structure(c(3L, 1L, 2L), .Label = c("Barry", "Dick", "Hal"), class = "factor"), V4 = structure(c(1L, 3L, 2L), .Label = c("Guy", "Jean-Paul", "Wally"), class = "factor"), V5 = structure(c(3L, 1L, 2L), .Label = c("Bart", "Damien", "John"), class = "factor")), .Names = c("V1", "V2", "V3", "V4", "V5"), class = "data.frame", row.names = c(NA, -3L))
setDT(DT)
setkey(DT, V1)

我正在尝试将 selcol 中的选定列( DT )粘贴在一起到一个新列。
selcol = c("V3", "V4")

我知道 DT[, "NEW" := paste0(V3, V4), with = FALSE]诀窍。但我想用 selcol在代码中。

我已经尝试了以下
DT[, "NEW" := paste0(which(colnames(DT) %in% selcol)), with = TRUE]
DT[, "NEW" := paste0(which(colnames(DT) %in% selcol)), with = TRUE]
DT[, "NEW" := paste0(3, 4), with = TRUE]
DT[, "NEW" := paste(3, 4), with = TRUE]

如何使用 data.table 执行此操作.

最佳答案

DT[, NEW := do.call(paste0, .SD), .SDcols = selcol] 
# V1 V2 V3 V4 V5 NEW
#1: S01 Alan Hal Guy John HalGuy
#2: S02 Jay Barry Wally Bart BarryWally
#3: S03 Bruce Dick Jean-Paul Damien DickJean-Paul

关于r - data.table 按索引粘贴选定的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28019904/

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