lexical scope - passing model parameters to R's predict() function robustly -
i trying use r fit linear model , make predictions. model includes constant side parameters not in data frame. here's simplified version of i'm doing:
dat <- data.frame(x=1:5,y=3*(1:5)) b <- 1 mdl <- lm(y~i(b*x),data=dat) unfortunately model object suffers dangerous scoping issue: lm() not save b part of mdl, when predict() called, has reach environment b defined. thus, if subsequent code changes value of b, predict value change too:
y1 <- predict(mdl,newdata=data.frame(x=3)) # y1 == 9 b <- 5 y2 <- predict(mdl,newdata=data.frame(x=3)) # y2 == 45 how can force predict() use original b value instead of changed one? alternatively, there way control predict() looks variable, can ensure gets desired value? in practice cannot include b part of newdata data frame, because in application, b vector of parameters not have same size data frame of new observations.
please note have simplified relative actual use case, need robust general solution , not ad-hoc hacking.
eval(substitute value quoted expression
mdl <- eval(substitute(lm(y~i(b*x),data=dat), list(b=b))) mdl # call: # lm(formula = y ~ i(1 * x), data = dat) # ...
Comments
Post a Comment