Alter a function as a parameter before evaluating it in R?

Posted by Shane on Stack Overflow See other posts from Stack Overflow or by Shane
Published on 2010-04-06T20:39:35Z Indexed on 2010/04/06 21:33 UTC
Read the original article Hit count: 210

Is there any way, given a function passed as a parameter, to alter its input parameter string before evaluating it?

Here's pseudo-code for what I'm hoping to achieve:

test.func <- function(a, b) {
    # here I want to alter the b expression before evaluating it:
    b(..., val1=a)
}

Given the function call passed to b, I want to add in a as another parameter without needing to always specify ... in the b call. So the output from this test.func call should be:

test.func(a="a", b=paste(1, 2))
"1"  "2"  "a"

Edit:

Another way I could see doing something like this would be if I could assign the additional parameter within the scope of the parent function (again, as pseudo-code); in this case a would be within the scope of t1 and hence t2, but not globally assigned:

t2 <- function(...) {
  paste(a=a, ...)
}

t1 <- function(a, b) {
  local( { a <<- a; b } )
}

t1(a="a", b=t2(1, 2))

This is somewhat akin to currying in that I'm nesting the parameter within the function itself.

Edit 2:

Just to add one more comment to this: I realize that one related approach could be to use "prototype-based programming" such that things would be inherited (which could be achieved with the proto package). But I was hoping for a easier way to simply alter the input parameters before evaluating in R.

© Stack Overflow or respective owner

Related posts about r

    Related posts about lazy-evaluation