簡體   English   中英

連接 R data.table 中的列名向量

[英]Concatenating a vector of column names in R data.table

我希望向data.table添加一列,該列是其他幾列的串聯,我將這些列的名稱存儲在向量cols 根據https://stackoverflow.com/a/21682545/1840471我試過do.call + paste但無法讓它工作。 這是我嘗試過的:

# Using mtcars as example, e.g. first record should be "110 21 6"
dt <- data.table(mtcars)
cols <- c("hp", "mpg", "cyl")
# Works old-fashioned way
dt[, slice.verify := paste(hp, mpg, cyl)]
# Raw do.call+paste fails with message:
# Error in do.call(paste, cols): second argument must be a list
dt[, slice := do.call(paste, cols)]
# Making cols a list makes the column "hpmpgcyl" for each row
dt[, slice := do.call(paste, as.list(cols))]
# Applying get fails with message:
# Error in (function (x) : unused arguments ("mpg", "cyl")
dt[, slice := do.call(function(x) paste(get(x)), as.list(cols))]

感謝幫助 - 謝謝。

類似問題:

我們可以使用mget將 'cols' 中元素的值作為list

dt[, slice := do.call(paste, mget(cols))]
head(dt, 2)
#   mpg cyl disp  hp drat    wt  qsec vs am gear carb    slice
#1:  21   6  160 110  3.9 2.620 16.46  0  1    4    4 110 21 6
#2:  21   6  160 110  3.9 2.875 17.02  0  1    4    4 110 21 6

或者另一種選擇是在.SDcols指定“cols”並paste .SD

dt[, slice:= do.call(paste, .SD), .SDcols = cols]
head(dt, 2)
#   mpg cyl disp  hp drat    wt  qsec vs am gear carb    slice
#1:  21   6  160 110  3.9 2.620 16.46  0  1    4    4 110 21 6
#2:  21   6  160 110  3.9 2.875 17.02  0  1    4    4 110 21 6

使用 apply 遇到了一個可能更簡單的解決方案,如下所示:

df[, "combned_column"] <- apply(df[, cols], 1, paste0, collapse = "")

可能不適用於 data.tables,但它做了我需要的,也可能是這里需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM