首页 > 解决方案 > 在 j 中同时使用列名向量和硬编码列

问题描述

(我永远无法完全记住j在 中是如何评估的,data.table每次我需要在 中调用变量定义的列时,我都j必须 对找到合适的组合....()c()get()with=FALSE..

我需要选择一些列并添加从其他列计算的一列,如下所示:

require(data.table)
data("mtcars")
setDT(mtcars)

mtcars[,.(mpg,   cyl,disp,  newcol=carb*3)]
#     mpg cyl  disp newcol
# 1: 21.0   6 160.0     12
# 2: 21.0   6 160.0     12
# 3: 22.8   4 108.0      3
# 4: 21.4   6 258.0      3
# 5: 18.7   8 360.0      6

但是,我的问题是某些列名存储在字符向量中:

mycols <- c('cyl', 'disp')
mycol3 <- 'carb'

...而另一个变量 ,mpg以交互方式提供(“硬编码”)。我正在尝试类似的东西

mtcars[,c('mpg',   mycols,  'newcol' = 'mycol3'*3)]
# Error in "mycol3" * 3 : non-numeric argument to binary operator

mtcars[,c('mpg',   mycols,  'newcol' = mycol3*3), with=FALSE]
# Error in mycol3 * 3 : non-numeric argument to binary operator

mtcars[,.(mpg,   get(mycols), newcol = get(mycol3)*3)]
# not an error but not the desired output:
#     mpg V2 newcol
# 1: 21.0  6     12
# 2: 21.0  6     12
# 3: 22.8  4      3
# 4: 21.4  6      3
# 5: 18.7  8      6

到目前为止,我找到了一种解决方法,但它真的很难看:

mtcars[ , c('mpg',   mycols,  mycol3), with=F
        ][ , ('newcol') := get(mycol3)*3
           ][ , c('mpg',mycols,'newcol'), with=F]

什么是正确的方法?

标签: rdata.table

解决方案


这样做的一种方法是data.table

  1. 添加新列。

  2. 选择所有需要的列。

library(data.table)

df <- mtcars
setDT(df)
cols <- c('mpg', mycols, 'newcol')
df[, newcol := get(mycol3)*3]
df[ , ..cols]

#    mpg cyl  disp newcol
#1: 21.0   6 160.0     12
#2: 21.0   6 160.0     12
#3: 22.8   4 108.0      3
#4: 21.4   6 258.0      3
#5: 18.7   8 360.0      6
#6: 18.1   6 225.0      3
#...
#...

如果您想在单行中执行此操作:

df[, newcol := get(mycol3)*3][, ..cols]

推荐阅读