[R] Weird feature when creating function lists with apply

Uffe Høgsbro Thygesen uht at dfu.min.dk
Wed Oct 10 11:13:48 CEST 2001


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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Uffe H. Thygesen, M.Sc.&Eng., Ph.D.
Danish Institute of Fisheries Research
http://www.dfu.min.dk


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