如何定义(参数)函数列表(使用local())

时间:2014-03-05 10:18:06

标签: r

我的目标是根据(不同的)参数定义功能列表。如 例如,考虑具有第i个列表元素的幂函数列表 第i个幂函数x ^ i。这是我试过的:

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

我有两个问题:

1)为什么版本3工作(虽然tmp不是真的 使用)?

2)对于这种类型的问题,最直观的方法是什么(我假设s.th.使用local()但可能比版本2/3更方便)

0 个答案:

没有答案