Closure and lm in R -
hi tried prepare little demo code closures in r when stumbled odd behavior. using debug realize failure happens due fact inside of lm line being executed
mf <- eval(mf, parent.frame()) however seems defeat functional aspect of programming closures ?
what missing ? here little example
# typical closure use foo <- function(formula,data,weight=null) { if(is.null(weight)) w=ones(nrow(data),1) else w=weight force(w) lm(formula,data,weights=w) } setup_something <- function(...) { function(formula,data) { foo(formula,data,...) } } # set our model function model <- setup_something() # set our data df = data.frame(x=seq(1,10,1),y=c(1:10)^1.5 * 3 + 2) model(y~x,df) error in eval(expr, envir, enclos) : object 'w' not found
instantiating formula (i.e.x~y) captures both environment created in, in cases happens in parent.frame() of call model().
if want subjugate environment, can explicitly adding line right before call lm(formula,data,weights=w):
# explicitly replace formula's environment current frame attr(formula,'.environment') <- sys.frame(sys.nframe()) or implicitly by replacing call lm(formula,data,weights=w) with:
#instantiate new forumla based on existing formula lm(stats::formula(unclass(formula)),data,weights=w) by way of background, if stick following line lm() right before call mf <- eval(mf, parent.frame()):
print(ls(envir=parent.frame())) you list of object names includes "w". however, 'mf' object being evaluated stats::model.frame line:
mf[[1l]] <- quote(stats::model.frame) and stats::model.frame evaluates arguments mf in context of .environment attribute of formula.
Comments
Post a Comment