Saturday, 10 August 2013

accumulating functions and closures in R

accumulating functions and closures in R

I am constructing successive approximation function using adaboost. I
would like to create the learning function along the way, and not to apply
directly to my test data.
unfortunately, it seems that R updates the value to which a variable name
refers to long after it is used.
#defined in plyr as well
id <- function(x) {x}
#my first classifier
modelprevious <- function(inputx, k) { k(0)}
#one step of my superb model
modelf <- function(x) 2*x #for instance
#I update my classifier
modelcurrent <- function(inputx, k)
{ modelprevious(inputx, function(res) {k(res +
modelf(inputx))})}
#it works
modelCurrent(2,id) #4
#Problem
modelf <- function(x) 3*x
modelCurrent(2,id) #6 WTF !!
The same function with the same argument return something different, which
is quite annoying ! So how is it possible to capture the value represented
by modelf so that the resulting function only depends on its argument at
the time of the binding, and not of some global state ?

No comments:

Post a Comment