[R] Curious behaviour of lapply and lists of functions
Julio Sergio Santana
juliosergio at gmail.com
Thu Jan 16 01:58:48 CET 2014
Let's say I define a simple list of functions, as follows
lf <- list(
function(x) x+5,
function(x) 2*x
)
Then I can take any individual function from the list and
use it with any value, as it is shown:
lf[[1]](3)
[1] 8
lf[[2]](3)
[1] 6
this gives me the results I expected.
Then I create a function producer, that just generates a new function
from a given one:
Producer <- function(f) function(x) 1/f(x)
if I use it with the elements of the list of functions
Producer(lf[[1]])(3)
[1] 0.125
Producer(lf[[2]])(3)
[1] 0.1666667
again, the result is satisfactory.
However, if I try to produce a list of the new functions, this is
what I get
linv <- lapply(lf, Producer)
linv[[1]](3)
[1] 0.1666667
linv[[2]](3)
[1] 0.1666667
Of course this is not what I wanted.
Could anyone explain me this courious behaviour, and how to get
the two functions in linv?
Thanks,
-Sergio.
More information about the R-help
mailing list