gpt4 book ai didi

r - 连接 R data.table 中的列名向量

转载 作者:行者123 更新时间:2023-12-04 09:16:29 24 4
gpt4 key购买 nike

我想在 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))]

感谢帮助 - 谢谢。

类似问题:
  • Concatenate columns and add them to beginning of Data Frame (使用 data.framescbinddo.call 上运行 - 这在我的 data.table 上非常慢)
  • R - concatenate row-wise across specific columns of dataframe (不将列作为名称或大量列处理)
  • Accessing columns in data.table using a character vector of column names (考虑使用列名聚合)
  • 最佳答案

    我们可以使用 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

    关于r - 连接 R data.table 中的列名向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38137436/

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