[R] programming creating different functions in a loop

Florin Maican florin.maican at handels.gu.se
Thu Mar 26 16:17:47 CET 2009


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 ---




More information about the R-help mailing list