Skip to content
Back to formatted view

Raw Message

Message-ID: <20090326161747.2455d1a8@mgf.econ.gu.se>
Date: 2009-03-26T15:17:47Z
From: Florin Maican
Subject: 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 ---