3

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 :/

Rcoster
  • 3,170
  • 2
  • 16
  • 35
  • What are you actually trying to do? – Thomas Aug 19 '13 at 19:48
  • 1
    I'm sure it's possible. The real question is why you would want that. `with` is for interactive use. – Roland Aug 19 '13 at 19:49
  • 1
    what exactly are you trying to do? – Fernando Aug 19 '13 at 19:58
  • I just wanna save dozens of line like `dados$index <- dados$v1 + dados$v2` (like the example, my indexes are more complicated) adding the formula to the function's call. You can change `with()` for `evalq()`, or anything that works. – Rcoster Aug 19 '13 at 20:05
  • There's probably an easier (and less buggy) way to do what you're trying to do than creating this function. – Señor O Aug 19 '13 at 20:16
  • I still don't understand. `lapply(list_of_data.frames, function(df) {df$index <- df$v1 + df$v2; df})`? – Roland Aug 19 '13 at 20:20
  • v1 and v2 are only examples. I have tons of indexes, some are directly the variable and others are functions of 2 or more variables (with names from V0001 to V1100). I have a functions that return the data frame with only the columns I need, and now I want add the 'feature' to compute the index inside the function. – Rcoster Aug 19 '13 at 20:26
  • It may also help you to read my question, & the answers, here: [R function to make table won't work](http://stackoverflow.com/questions/17600713/) – gung - Reinstate Monica Aug 20 '13 at 01:19

1 Answers1

3

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
Fernando
  • 7,785
  • 6
  • 49
  • 81
  • Almost there! Any idea how to allow `funcao` be a string? `as.expression()` didn't work – Rcoster Aug 19 '13 at 20:14
  • Perfect! I just changed the function to `func <- function(data, funcao) { funcao <- parse(text=funcao) ; return(with(data, eval(funcao))) }` so I can use directly a string. Thanks! – Rcoster Aug 19 '13 at 20:32