ect.org] On
Behalf Of Greg Snow
Sent: Thursday, March 26, 2009 9:54 AM
To: Bert Gunter; 'Florin Maican'; r-help@r-project.org
Subject: Re: [R] programming creating different functions in a loop
But wrong questions requiring complicated answers are sometimes more fun
:-).
One difference
n...@r-
> project.org] On
> Behalf Of Greg Snow
> Sent: Thursday, March 26, 2009 9:25 AM
> To: Florin Maican; r-help@r-project.org
> Subject: Re: [R] programming creating different functions in a loop
>
> Anytime that you are tempted to use assign and a loop, you should
> consid
] programming creating different functions in a loop
Anytime that you are tempted to use assign and a loop, you should consider
using lapply (or sapply) and a list instead.
Consider this alternative:
> f <- lapply( 1:3, function(i){ force(i); function(x) x+i} )
>
> f[[1]](3)
[1] 4
>
Anytime that you are tempted to use assign and a loop, you should consider
using lapply (or sapply) and a list instead.
Consider this alternative:
> f <- lapply( 1:3, function(i){ force(i); function(x) x+i} )
>
> f[[1]](3)
[1] 4
> f[[2]](10)
[1] 12
> f[[3]](0)
[1] 3
>
> sapply( f, function(f)
Thanks Luke!
It works! My mistake was that I used "local binding" only for "i" and
not for the whole function.
Best regards,
Florin
On Thu, 26 Mar 2009 10:57:21 -0500 (CDT)
l...@stat.uiowa.edu wrote:
> for() does not creae separete bindings for the index each iteration,
> so the function bodi
for() does not creae separete bindings for the index each iteration,
so the function bodies see the global binding of i, which in this case
will be the final value. One possible solution is to use local(), e.g.
for(i in 1:3){
assign(paste("f",i,sep=""),
local({
k <- i
6 matches
Mail list logo