[R] Weird feature when creating function lists with apply

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Oct 10 11:34:58 CEST 2001


On Wed, 10 Oct 2001, [iso-8859-1] Uffe Høgsbro Thygesen wrote:

> Hi R-fellows,
>
> can anyone explain this weird feature? I am trying to create a list of
> functions with apply, and it appears that there is something strange going
> on when the function evaluates the argument a. When I duplicate a into a
> local variable b, the result changes !?!
>
> Any pointers? Thank in advance. Cheers,
>
> Uffe
>
>
> # Create a function which returns a function
> > f1 <- function(a) {return(function(x) a*x)}
> # Create a list of functions, parameterised by 1:4
> > apply(as.array(1:4),1,f1)[[2]](1)
> [1] 4
>
> # Repeat
> > f2 <- function(a) {b <- a ;return(function(x) b*x)}
> > apply(as.array(1:4),1,f2)[[2]](1)
> [1] 2

I don't think this is what you intended.

ll <- apply(as.array(1:4),1,f1)
ll
[[1]]
function(x) a*x
<environment: a6d374>

[[2]]
function(x) a*x
<environment: a6d09c>

[[3]]
function(x) a*x
<environment: a6dd60>

[[4]]
function(x) a*x
<environment: a6da88>

which is not what your comment implies.

And
> get("a", envir=environment(ll[[2]]))
[1] 4

shows why they differ.


1) This is a strange way to produce a list via arrays:
ll <- lapply(1:4, f1) is what is normally used.

2) I think what you really wanted was

f3 <- function(a) substitute(function(x) a*x, list(a = a))
lapply(1:4, f3)
[[1]]
function(x) 1 * x

[[2]]
function(x) 2 * x

[[3]]
function(x) 3 * x

[[4]]
function(x) 4 * x

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

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