有一种方法可以将参数从函数传递给with()
吗?类似的东西:
dados <- data.frame(x=1:10, v1=rnorm(10), v2=rnorm(10))
with(dados, v1+v2) # Works
func <- function(data, funcao) {
with(data, funcao)
}
func(dados, v1+v2) # Fails
func(dados, 'v1+v2') # Fails
我已经尝试使用eval()
,但它也失败了:/
答案 0 :(得分:3)
好的,我想我明白了。您需要在 func 中调用 eval ,然后传递表达式:
dados <- data.frame(x=1:10, v1=rnorm(10), v2=rnorm(10))
func <- function(data, funcao) {
with(data, eval(funcao))
}
func(dados, expression(v1+v2))
[1] -0.9950362 1.0934899 -0.9791810 -1.2420633 -1.0930204 0.8941630 -2.3307571 -1.5012386 3.2731584 0.2585419
使用字符串:
x = "v1 + v2"
func(dados, parse(text=x))
[1] -0.9950362 1.0934899 -0.9791810 -1.2420633 -1.0930204 0.8941630 -2.3307571 -1.5012386 3.2731584 0.2585419