[R] Putting an index explicitly into function code --- a curiosity.

Rolf Turner rolf.turner at xtra.co.nz
Sat Jan 7 03:43:55 CET 2012


I want to create a list of functions in a for loop, with the index
of the loop appearing explicitly in the function code.

After quite a bit of thrashing around I figured out how to do it.

Here is a toy example:

junk <- vector("list",4)
for(i in 1:4) {
     itmp <- i
     junk[[i]] <- eval(bquote(function(x){42 + .(itmp)*x}))
}

So I'm *basically* happy, but there's something I don't understand:
Why do I need "itmp"?

That is, if I do

junk <- vector("list",4)
for(i in 1:4) {
     junk[[i]] <- eval(bquote(function(x){42 + .(i)*x}))
}

then every entry of "junk" is equal to

function (x)
{
     42 + 4L * x
}

i.e. I seem to get the *last* value of the index always substituted, 
rather than
the "current" value.  Something (subtle?) is going on that I don't 
understand.
And than makes me feel not quite comfy.  Can anyone enlighten me?

Ta.

     cheers,

         Rolf Turner

P. S.  Also:  Is there a *better* way of accomplishing my objective than 
what I came up with?

         R. T.



More information about the R-help mailing list