Reputation: 3210
There is a way to pass a parameter from a function to with()
? Something like:
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 :/
Upvotes: 3
Views: 104
Reputation: 7895
Ok, i think i got it. You need to call eval inside func and then pass an expression:
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
Upvotes: 3