Re: [R] Creating a list of functions

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Thu, 05 Jun 2008 11:20:40 -0400

On 6/5/2008 10:50 AM, Andreas Posch wrote:
> I've been trying to create a list of function where function[[i]] should actually return the value of i.
>
> trying:
>
> func <- vector("list",2)
> i <- 1
> while (i <= 2)
> {
> func[[i]] <- function()
> {
> i
> }
> i <- i+1
> }
>
> however only returned the last value of i for each function. Any help how to achieve the solution intended would be greatly appreciated.
>
> thanks in advance,
>
> andreas posch

The problem is that the function definition

function() { i }

has no local variable i, so it looks in the enclosing environment for one, and they all find the same one. The usual way to do what you want is to create a builder function, like this:

builder <- function(i) {

   return( function() i )
}

When the anonymous function looks for i, it will find the local one in the builder. Each call to the builder will create a different local value of i.

So then your loop would be

while (i <= 2) {

   func[[i]] <- builder(i)
   i <- i + 1
}

I hope this helps.

Duncan Murdoch



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. Received on Thu 05 Jun 2008 - 17:25:37 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 05 Jun 2008 - 17:30:37 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive