[R] programming creating different functions in a loop

Greg Snow Greg.Snow at imail.org
Thu Mar 26 17:24:55 CET 2009


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) f(1:10) )
      [,1] [,2] [,3]
 [1,]    2    3    4
 [2,]    3    4    5
 [3,]    4    5    6
 [4,]    5    6    7
 [5,]    6    7    8
 [6,]    7    8    9
 [7,]    8    9   10
 [8,]    9   10   11
 [9,]   10   11   12
[10,]   11   12   13

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Florin Maican
> Sent: Thursday, March 26, 2009 9:18 AM
> To: r-help at r-project.org
> Subject: [R] programming creating different functions in a loop
> 
> 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  Maican
> ==================================
> 
> 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 ---
> 
> ______________________________________________
> 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.




More information about the R-help mailing list