1

I made a model (mod1) using variables from my data but when I try to use that model to make a prediction I get the error message "object 'gop' not found".

mod2 <- stan_glm(filisave ~ gop + running18 + wings + leader + stdrank + servedmin + gop:running18, data = dodgingrules, refresh = 0)enter code here

new_data <- data.frame(dodgingrules$gop, dodgingrules$running18)

y_point_pred <- predict(mod2, newdata=new_data)

The first two lines run without issue, but with the last one I get the error message "object 'gop' not found". Not sure where the error lies. I'm very new to R so entirely possible that I'm making this more difficult than it needs to be.

1
  • You should include which packages are you using as well as your data. If you data set is large, take a small sample (e.g., include only 2 independent variables)
    – Nikos
    Commented Oct 31, 2022 at 21:06

1 Answer 1

1

You are functionally pulling vector from the source data.frame so, they are not inheriting their names and the resulting call to predict sees them as missing. This should work in addressing your immediate problem.

new_data <- data.frame(gop=dodgingrules$gop, running18=dodgingrules$running18)

However, creating a new data.frame for back-prediction is not necessary as you can just pass dodgingrules to the newdata argument. For most predict functions you can even have spurious columns (not in model) as the function will pull the relevant columns but, if you want to specify specific columns you can index them on the fly ie.,

predict(mod2, newdata=dodgingrules[,c("gop","running18")]).

For back prediction, unless you are calling some different arguments or passing data that is different from what was used in the model, the results will be the same as what the model object contains, in this case "mod2$fitted.values". The rstanarm::stan_glm function returns a stanreg object with several useful objects eg., residuals, linear.predictors (same as fitted.values if a linear model) and, prior.info containing the prior distributions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.