# [R] Defining functions inside loops

Greg Snow Greg.Snow at imail.org
Mon Nov 15 21:56:49 CET 2010

```This is a side effect of the lazy evaluation done in functions.  Look at the help page for the force function for more details and how to force evaluation and solve your problem.

--
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 Eduardo de Oliveira Horta
> Sent: Monday, November 15, 2010 1:50 PM
> To: r-help at r-project.org
> Subject: [R] Defining functions inside loops
>
> Hello,
>
> I was trying to define a set of functions inside a loop, with the loop
> index
> working as a parameter for each function. Below I post a simpler
> example, as
> to illustrate what I was intending:
>
> f<-list()
> for (i in 1:10){
>   f[[i]]<-function(t){
>     f[[i]]<-t^2+i
>   }
> }
> rm(i)
>
> With that, I was expecting that f[[1]] would be a function defined by
> t^2+1,
> f[[2]] by t^2+2 and so on. However, the index i somehow doesn't "get
> in" the
> function definition on each loop, that is, the functions f[[1]] through
> f[[10]] are all defined by t^2+i. Thus, if I remove the object i from
> the
> workspace, I get an error when evaluating these functions. Otherwise,
> if
> don't remove the object i, it ends the loop with value equal to 10 and
> then
> f[[1]](t)=f[[2]](t)=...=f[[10]](t)=t^2+10.
>
> I am aware that I could simply put
>
> f<-function(u,i){
>   f<-t^2+i
> }
>
> but that's really not what I want.
>
> Any help would be appreciated. Thanks in advance,
>
> Eduardo Horta
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help