Skip to content
Prev 302518 / 398503 Next

Force evaluation of a symbol when a function is created

Both of those approaches require the function to be created
at the same time that the environment containing some of its
bindings is created.  You can also take an existing function and
assign a new environment to it.  E.g.,

  > f <- function(x) y * x
  > ys <- c(2,3,5,7,11)
  > fs <- lapply(ys, function(y) {
                          env <- new.env(parent=baseenv());
                          env[["y"]] <- y ;
                          environment(f) <- env ; f })
  > # fs is a list of functions, all identical except for their environments, which contain 'y'.
  > fs[[2]]
  function (x) 
  y * x
  <environment: 0x0000000005df1c38>
  > fs[[2]](10)
  [1] 30
  > fs[[3]]
  function (x) 
  y * x
  <environment: 0x0000000005def8c0>
  > fs[[3]](10)
  [1] 50

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com