r - 在 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]
什么是正确的方法?
解决方案
这样做的一种方法是data.table
:
添加新列。
选择所有需要的列。
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]
推荐阅读
- ios - 更改导航栏背景颜色后,self.view 的 y 位置发生更改
- xaml - 如何向我的 xaml 2017 VS 程序添加图标
- java - 如何在mig布局中进行组件定位
- webpack - 仅使用标志运行 Webpack 插件
- c - 关于数据结构的建议
- printing - 打印 itext 7 pdf 文档(最好通过 system.drawing.printing)
- typescript - Typescript:使用联合类型和三元运算符进行类型推断
- kubernetes - Kubernetes DNS 使用 systemd resolvd 的理想设置
- html - 如何在视频背景上覆盖导航栏
- charts - chartjs默认背景颜色到列