[R] programming creating different functions in a loop
Florin Maican
florin.maican at handels.gu.se
Thu Mar 26 17:16:06 CET 2009
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)
luke at stat.uiowa.edu wrote:
> 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 # create local binding with current loop
> index value function(x) x + k
> }))
> }
>
>
> luke
>
>
> On Thu, 26 Mar 2009, Florin Maican wrote:
>
> > Hi
> >
> > I want to create the following functions in a loop
> >
> > f1<-function(x){x+1}
> > f2<-function(x){x+2}
> > f3<-function(x){x+3}
> >
> > Output f1(2)=3
> > f2(2)=4
> > f3(2)=5
> >
> >
> > I tried to create the in a loop as bellow but I get wrong on answers
> > because the value of i change
> >
> > for(i in 1:3){
> > assign(paste("f",i,sep="")
> > ,function(x)
> > x+i
> > )
> > } # end for
> >
> > Output f1(2)=5
> > f2(2)=5
> > f3(2)=5
> > But it is not what I want. The question is how I can
> > fix in R the value of "i" in my functions? I tried to use assign()
> > and get(),but I did not manage.
> >
> > Thanks in advance,
> > Florin
> >
> >
>
--
Florin G. Maican
==================================
Ph.D. candidate,
Department of Economics,
School of Business, Economics and Law,
Gothenburg University, Sweden
-----------------------------------
P.O. Box 640 SE-405 30,
Gothenburg, Sweden
Mobil: +46 76 235 3039
Phone: +46 31 786 4866
Fax: +46 31 786 4154
Home Page: http://maicanfg.googlepages.com/index.html
E-mail: florin.maican at handels.gu.se
------------------------------------
"Not everything that counts can be
counted, and not everything that can be
counted counts."
--- Einstein ---
More information about the R-help
mailing list