Julio Sergio Santana
2014-Jan-16 00:58 UTC
[R] Curious behaviour of lapply and lists of functions
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.
Julio Sergio Santana
2014-Jan-16 01:20 UTC
[R] Curious behaviour of lapply and lists of functions
Julio Sergio Santana <juliosergio <at> gmail.com> writes:> ... > Producer <- function(f) function(x) 1/f(x) >Counsulting a previous post, I got to the solution, I just need to rewrite the function Producer forcing it to eavaluate its argument, as follows Producer <- function(f) {f ;function(x) 1/f(x)} Then, linv <- lapply(lf, Producer) linv[[1]](3) [1] 0.125 linv[[2]](3) [1] 0.1666667 Which is the desired result. Thanks everybody for reading. -Sergio.