Skip to content

substituting values into a function

2 messages · Thomas Yee, Peter Dalgaard

#
Hi everybody,

In Splus, the following works fine.

foo1 <- function(x, const)
    x + const

foo2 <- function(x, const)
    x * const

const1 <- 1
const2 <- 2
foo <- substitute(function(x) {
    a <- foo1(x, const1)
    b <- foo2(a, const2)
    b
}, list(const1=const1, const2=const2))

foo(1:3)

In R, the code doesn't work, as foo is of mode "call", and
as.function(foo) gives an error. I could add the arguments const1 and
const2 to foo, but that would be less elegant for me.  Also, it would
be needful to have the same code running in both S and R.  Assistance
with the problem would be greatly appreciated. Thanks in advance.

Thomas 



-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
Thomas Yee <yee at scitec.auckland.ac.nz> writes:
I'm surprised that it works in S... 

Substitute generally returns an unevaluated expression (== object of
mode call), in this case a call to the function constructor, not the
function itself. Apparently, S does not make that distinction, but
you'd get in the same situation there if you did
Error: couldn't find function "x"

The solution is to evaluate the call object first:
[1] 4 6 8

BTW, there's a much nicer way in R, using lexical scope:

foo <- local({
  foo1 <- function(x, const)
    x + const
 
  foo2 <- function(x, const)
    x * const
 
  const1 <- 1
  const2 <- 2
  function(x) {
     a <- foo1(x, const1)
     b <- foo2(a, const2)
     b
  }
})
[1] 4 6 8
[1] 22 24 26