[R] programming creating different functions in a loop

luke at stat.uiowa.edu luke at stat.uiowa.edu
Thu Mar 26 16:57:21 CET 2009


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

-- 
Luke Tierney
Chair, Statistics and Actuarial Science
Ralph E. Wareham Professor of Mathematical Sciences
University of Iowa                  Phone:             319-335-3386
Department of Statistics and        Fax:               319-335-3017
    Actuarial Science
241 Schaeffer Hall                  email:      luke at stat.uiowa.edu
Iowa City, IA 52242                 WWW:  http://www.stat.uiowa.edu




More information about the R-help mailing list