替代(m)获取data.table函数 [英] Alternative to (m)get in data.table functions
问题描述
假设我具有以下 data.table
,并希望通过引用存储在向量中的变量来获取以下输出:
Let's say I have the following data.table
and would like to get the output below by referring to variables stored in a vector:
dt <- data.table(a = rep(1, 3),
b = rep(2, 3))
x <- 'a'
y <- 'b'
dt[, .(sum(get(x)), mean(get(y)))]
V1 V2
1: 3 2
很酷,它有效.但是现在我想做一个函数,然后做类似的事情:
Cool, it works. But now I'd like to make a function, and then do something like:
foo <- function(arg1, arg2) {
dt[, .(sum(get(arg1)), mean(get(arg2)))]
}
foo(x, y)
意识到它的工作原理,我想避免调用所有这些 gets
,并执行以下操作:
Realizing it works, I'd like to avoid calling all those gets
, and do something like:
foo <- function(arg1, arg2) {
eval(substitute(dt[, .(sum(arg1), mean(arg2))]))
}
foo(x, y) # or foo('x', 'y')
但是这失败了.是否有关于如何像多次调用 get
一样一次评估所有参数的想法?
But this fails. Any idea on how to evaluate all the arguments at once in a way similar to calling get
multiple times?
推荐答案
我们可以使用 as.symbol
或 as.name
和 eval
uate
We can convert to sym
bol with as.symbol
or as.name
and eval
uate
foo <- function(arg1, arg2) {
dt[, .(sum(eval(as.name(arg1))), mean(eval(as.name(arg2))))]
}
foo(x, y)
# V1 V2
#1: 3 2
或使用 [[
]来对数据表的列进行子集化
Or use [[
to subset the columns of the data.table
foo <- function(arg1, arg2) {
dt[, .(sum(.SD[[arg1]]), mean(.SD[[arg2]]))]
}
foo(x, y)
# V1 V2
#1: 3 2
或者另一个选择是粘贴
和 eval/parse
foo <- function(arg1, arg2) {
eval(parse(text = paste0("dt[, .(sum(", arg1, "), mean(", arg2, "))]")))
}
foo(x, y)
# V1 V2
#1: 3 2
这篇关于替代(m)获取data.table函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!