[R] saving a regression model to a file
Marc Schwartz
marc_schwartz at me.com
Thu Apr 14 19:57:59 CEST 2011
On Apr 14, 2011, at 12:45 PM, Alison Callahan wrote:
> Hello all,
>
> First off, I am using R version 2.13.0 in Ubuntu.
>
> I have read previous posts in the R mailing list on saving models for
> later use, and the responses indicate using the R save() function to
> save a model and then using load() to load it is one way to go.
> However, when I use the save() function to save a model to a file, and
> then try to load it using load(), the loaded "model" is just an object
> of class Character. Here is the relevant R code:
>
> #######creating the model#########
> data <- read.table("../synthetic_data_4.csv", header=TRUE, sep=",")
>
> data <- data.frame(data)
>
> data$type <- factor(data$type)
>
> pcrmodel <- pcr(formula=count~week+type+total, data=data, x=TRUE, y=TRUE)
>
> #########getting summary of model########
>
> summary(pcrmodel)
>
> Output:
>
> Data: X dimension: 318 4
> Y dimension: 318 1
> Fit method: svdpc
> Number of components considered: 4
> TRAINING: % variance explained
> 1 comps 2 comps 3 comps 4 comps
> X 99.57 100.00 100.00 100.00
> count 13.70 16.01 16.17 16.54
>
>
> ########saving the model#########
>
> save(pcrmodel, file='model.rda')
>
> ########loading the model#########
>
> model <- load('model.rda')
>
Your error is above, in that you are assigning the result of load() to a new object and presuming that the new object contains 'pcrmodel'.
If you look at ?load, you will see that the function returns a character vector of the names of the objects contained in the file you are loading.
Thus, 'model' is a character vector as show below, in this case, likely containing a single entry of "pcrmodel". Type:
model
at the R prompt....
If you use:
summary(pcrmodel)
after the load() call, you should get your normal model summary output. When using load(), it restores the saved objects in the file to the current workspace. If you use:
ls()
you should see 'pcrmodel' listed, along with anything else in your current workspace.
HTH,
Marc Schwartz
> ########getting summary of model after loading###########
>
> summary(model)
>
> Output:
>
> Length Class Mode
> 1 character character
>
> ##################################
>
> What am I doing wrong? Or is this not the correct way to save a model
> to be used later? Thanks,
>
> Alison
More information about the R-help
mailing list