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
Is this what you want:> func <- vector("list",2) > i <- 1 > while (i <= 2)+ { + func[[i]] <- local({ + z <- i + function(){ z } + }) + i <- i+1 + }> func[[1]]()[1] 1> func[[2]]()[1] 2>Your solution was using 'i' which picked up the last definition of 'i'. 'local' create a local copy of 'i' and uses that in the function. On Thu, Jun 5, 2008 at 10:50 AM, Andreas Posch <andreas.posch@boku.ac.at> 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 > > ______________________________________________ > R-help@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<http://www.r-project.org/posting-guide.html> > and provide commented, minimal, self-contained, reproducible code. >-- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem you are trying to solve? [[alternative HTML version deleted]]
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 poschThe 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