3

I have the following R Code (the last part of this question), after the last line I expect to get a list of 4 "retFun" functions, each initialized with a different x so that I get the following result

funList[[1]](1) == 7 #TRUE
funList[[2]](1) == 8 #TRUE

And so on, but what I seem to get is

funList[[1]](1) == 10 #TRUE
funList[[2]](1) == 10 #TRUE

As if each function in the list has the same x value

creatFun <- function(x, y)
{
  retFun <-  function(z)
  {
    z + x + y

  }
}


myL <- c(1,2,3,4)
funList <-sapply(myL, creatFun, y = 5)
StaticBug
  • 557
  • 5
  • 15

1 Answers1

6

This could be (and probably is, somewhere) an exercise on how lazy evaluation works in R. You need to force the evaluation of x before the creation of each function:

creatFun <- function(x, y)
{
    force(x)
  retFun <-  function(z)
  {
    z + x + y
  }
}

...and to be safe, you should probably force(y) as well for the times when you aren't passing a single value in for that parameter.

A good discussion can be found in Hadley's forthcoming book, particularly the section on lazy evaluation in the Functions chapter (scroll down).

joran
  • 169,992
  • 32
  • 429
  • 468