0

My goal is to define a list of functions depending on (different) parameters. As an example, consider a list of power functions with the ith list element being the ith power function x^i. Here is what I tried:

## Version 1: How one would think it works
f <- lapply(1:2, function(i) function(x) x^i))
c(f[[1]](3), f[[2]](3)) # => 9, 9 => wrong

## Version 2: I found out that the following works, but this is not very intuitive code (IMHO)
f <- lapply(1:2, function(i) local({ tmp <- i; function(x) x^tmp }))
c(f[[1]](3), f[[2]](3)) # => 3^1=3, 3^2=9

## Version 3: Interestingly, this works (but why?):
f <- lapply(1:2, function(i) local({ tmp <- i; function(x) x^i }))
c(f[[1]](3), f[[2]](3)) # => 3^1=3, 3^2=9

I have two questions:

1) Why does version 3 work (although tmp is not really used)?

2) What's the most intuitive approach to problems of this type (I assume s.th. with local() but maybe more convenient than Version 2/3)

Marius Hofert
  • 6,546
  • 10
  • 48
  • 102

0 Answers0