I want to build a model using R, save it and reloading it when required. I am able to save the model and reload it without any problem, however when i use the model along with predict statement, I am getting errors.

This is what i do:

set.seed(345) df <- data.frame(x = rnorm(20)) df <- transform(df, y = 5 + (2.3 * x) + rnorm(20))


m1 <- lm(y ~ x, data = df)

save this model

save(m1, file = "my_model1.rda")

a month later, new observations are available:

newdf <- data.frame(x = rnorm(20))

load the model


When i use the above model to predict for new values, I am getting output values as "NA"

predict(m1, newdata = newdf)

"NA" "NA" "NA" "NA" "NA" "NA" "NA" "NA" "NA"

I could able to see that the model has been loaded correctly by giving a print command


Call: lm(formula = y ~ x, data = df)

Coefficients: (Intercept) x
4.792 2.119

Is there anything that I miss here?

  • $\begingroup$ That should work! are you sure there's no typo, say in newdf? $\endgroup$ – Ehsan M. Kermani Jul 13 '15 at 17:43
  • $\begingroup$ @EhsanM.Kermani - Thanks for the reply, My code is similar one, as i could not copy that from my office network, i pasted this one. I did similar to this. $\endgroup$ – Arun Jul 13 '15 at 17:50
  • $\begingroup$ This is strange, b/c when you have the coefficients in this particular case then prediction is a simple algebra, but returning 'NA's should indicate a problem with new data not the loaded model! $\endgroup$ – Ehsan M. Kermani Jul 13 '15 at 18:04
  • $\begingroup$ @EhsanM.Kermani - Thanks again. The model works if i use directly in the same programme. (means, build model and predict immediately for a new data). Where as I get into this problem only when i save the model, load again and then use it for prediction. $\endgroup$ – Arun Jul 13 '15 at 18:48
  • $\begingroup$ @EhsanM.Kermani - as you said, this has worked. The issue which was preventing from working is, one of the old models which was still in the R's Cache memory. I have removed that using rm=list(ls)) which has solved the problem. Thanks you very much for your help. $\endgroup$ – Arun Jul 14 '15 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.