[R] Putting an index explicitly into function code --- a curiosity.
jim holtman
jholtman at gmail.com
Sat Jan 7 16:44:25 CET 2012
Here is yet another way of doing it using 'local':
> junk<- vector("list",4)
> for(i in 1:4) {
+ junk[[i]] <- local({
+ local_i <- i
+ function(x) 42 + local_i * x
+ })
+ }
> for (i in 1:4) cat(i, junk[[i]](1), '\n')
1 43
2 44
3 45
4 46
On Sat, Jan 7, 2012 at 10:38 AM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote:
> On Sat, Jan 7, 2012 at 10:23 AM, Duncan Murdoch
> <murdoch.duncan at gmail.com> wrote:
>> On 12-01-06 10:21 PM, Rolf Turner wrote:
>>>
>>> On 07/01/12 15:51, R. Michael Weylandt<michael.weylandt at gmail.com> wrote:
>>>>
>>>> I imagine the answer will involve lazy evaluation and require you use
>>>> force() but I'm not quite qualified to pronounce and not at a computer to
>>>> test.
>>>
>>>
>>> I think you've got it; I tried
>>>
>>> junk<- vector("list",4)
>>> for(i in 1:4) {
>>> junk[[i]]<- eval(bquote(function(x){42 + .(force(i))*x}))
>>> }
>>>
>>> and got the result that I wanted. Still don't completely understand, but
>>> it at least makes vague sense and makes me a bit more comfy.
>>
>>
>> I'm not so sure. The index in a for loop isn't supposed to be a promise.
>> To me, it looks like a bug, maybe in bquote()...
>>
>
> These two variations without bquote and the third which just replaces
> for with while all (that I had previously posted) do work:
>
> # 1
> junk <- vector("list",4)
> for(i in 1:4) {
> junk[[i]] <- eval(substitute(function(x) { 42 + i * x }, list(i = i)))
> }
> junk
>
> # 2
> junk <- vector("list",4)
> for(i in 1:4) {
> junk[[i]] <- eval(parse(text = paste("function(x) { 42 +", i, "*x }")))
> }
> junk
>
> # 3 - from my prior post
> junk <- vector("list",4)
> i <- 1
> while(i <= 4) {
> junk[[i]] <- eval(bquote(function(x){42 + .(i)*x}))
> i <- i + 1
> }
> junk
>
> --
> Statistics & Software Consulting
> GKX Group, GKX Associates Inc.
> tel: 1-877-GKX-GROUP
> email: ggrothendieck at gmail.com
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.
More information about the R-help
mailing list