[R] substituting values into a function

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sun Oct 10 23:42:47 CEST 1999


Thomas Yee <yee at scitec.auckland.ac.nz> writes:

> 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.

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

> x<-substitute(get("ls"))
> x()
Error: couldn't find function "x"

The solution is to evaluate the call object first:

> eval(foo)(1:3)
[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
  }
})

> foo(1:3)
[1] 4 6 8
> evalq(const1 <- 10, environment(foo))
> foo(1:3)
[1] 22 24 26



-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list