在R中的另一个函数中使用data.table [英] Use data.table within another function in R
问题描述
使用列创建新变量时,data.table不允许使用带引号的列名称。
在函数中使用data.table时会产生以下问题。
When creating a new variable with columns, data.table does not allow quoted column names. This yields the following problem when using a data.table within a function.
library(data.table)
dt <- data.table(var1 = c(1:10), var2 = seq(2,20,2), var3 = seq(40,4,-4))
addColumnsError <- function(dt, v1, v2){
dt[,v1 + v2]
}
addColumnsError(dt, var1, var2)
> Error in eval(jsub, SDenv, parent.frame()) : object 'var1' not found
addColumnsError(dt, "var1", "var2")
> Error in v1 + v2 : non-numeric argument to binary operator
的非数字参数以下解决方法可以解决此问题。 / p>
The following workaround handles this problem.
addColumns <- function(dt,v1,v2){
v1<-as.character(substitute(v1))
v2<-as.character(substitute(v2))
dt[,eval(parse(text=v1)) + eval(parse(text=v2))]
}
addColumns(dt, var1, var2)
[1] 3 6 9 12 15 18 21 24 27 30
addColumns(dt, "var1", "var2")
[1] 3 6 9 12 15 18 21 24 27 30
是否有一种更优雅的方式将列名传递给函数内的data.table对象?
Is there a more elegant way to pass column names to a data.table object within a function?
(注意:我可以只调用data.table函数但我打算进行更复杂的计算:))
(Note: I could just call the data.table function but I intend to make more complicated calculations :) )
推荐答案
如果要使用非标准评估,则需要类似替代
。但是,绝对没有理由使用 parse
。
If you want to use non-standard evaluation, you need something like substitute
. However, there is absolutely no reason for using parse
.
addColumnsError <- function(dt, v1, v2){
eval(substitute(dt[, v1 + v2]))
}
addColumnsError(dt, var1, var2)
#[1] 3 6 9 12 15 18 21 24 27 30
这篇关于在R中的另一个函数中使用data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!