Skip to content
Prev 324856 / 398503 Next

generate simple function with pre-defined constants

Try the following:
   generateABFunction <- function(a, b) {
      force(a)
      force(b)
      function(x) a*x + b
   }
   f12 <- generateABFunction(1, 2)
   f53 <- generateABFunction(5,6)
   f12(10:12) # get 12, 13, 14
   f53(10:12) # get 56, 61, 66

See, e.g., yesterday's discussion under the subject
"Trying to build up functions with its names by means of lapply"
on why the force() calls are required.  Read up on R's environments
to see why f12 and f53 look the same but act differently (hint:
look at ls.str(environment(f12))).

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com