通过函数将参数传递给with()

时间:2022-12-05 19:12:14

There is a way to pass a parameter from a function to with()? Something like:

有一种方法可以将参数从函数传递给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

I've already tried with eval(), but it fails too :/

我已经尝试使用eval(),但它也失败了:/

1 个解决方案

#1


3  

Ok, i think i got it. You need to call eval inside func and then pass an expression:

好的,我想我懂了。您需要在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

To use a string:

使用一个字符串:

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

#1


3  

Ok, i think i got it. You need to call eval inside func and then pass an expression:

好的,我想我懂了。您需要在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

To use a string:

使用一个字符串:

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