[R] User error in calling predict/model.frame
Russell Pierce
rpier001 at ucr.edu
Fri Jan 28 22:37:04 CET 2011
I want to predict values from an existing lm (linear model, e.g.
lm.obj) result in R using a new set of predictor variables (e.g.
newdata). However, it seems that because my linear models was made by
calling scale() on the target predictor that predict exits with an
error, "Error in scale(xxA, center = 9.7846094491829, scale =
0.959413568556403) : object 'xxA' not found". By debugging predict, I
can see that the error occurs in a call to model.frame. By debugging
model frame I can see the error occurs with this command: variables
<- eval(predvars, data, env); it seems likely that the error is
because predvars looks like this:
list(scale(xxA, center = 10.2058714830537, scale = 0.984627257169526),
scale(xxB, center = 20.4491690881149, scale = 1.13765718273923))
An example case:
dat <- data.frame(xxA = rnorm(20,10), xxB = rnorm(10,20))
dat$out <- with(dat,xxA+xxB+xxA*xxB+rnorm(20,20))
xVar <- "scale(xxA)"
traceVar <- "scale(xxB)"
DVname <- "out"
lm.obj <- lm.res.scale <- lm(out ~ scale(xxA)*scale(xxB),data=dat)
my.data <- lm.obj$model #load the data from the lm object
X1 <- my.data[,xVar]
X2 <- my.data[,traceVar]
DV <- lm.obj$model[,DVname]
newdata <- expand.grid(X1=c(-1,0,1),X2=c(-1,0,1))
newdata$X1 <- newdata$X1 * sd(my.data[,xVar])
newdata$X2 <- newdata$X2 * sd(my.data[,traceVar])
names(newdata) <- c(xVar,traceVar) #have to rename to original
variable names for predict to work
newdata$Y <- predict(lm.obj,newdata)
Is there something I could do before passing newdata or lm.obj to
predict() that would prevent the error? From the help file it looks
like I might be able to do something with the terms, argument but I
haven't quite figured out what I would need to do. Alternatively, is
there a fix for model.frame that would prevent the error? Should
predict() behave this way?
Thanks for your time,
Russell S. Pierce
More information about the R-help
mailing list