I would like to save a glm object in one R machine and use it for prediction on another data set located on another machine that has a newer data.I try to use save
and load
but with no success.What am I doing wrong? Here is a toy example:
# on machine 1:
glm<-glm(y~x1+x2,data=dat1, family=binomial(link="logit")
save(glm,file="glm.Rdata") # the file is stored in a folder.
# on machine 2:
load(glm.RData) # got an error:"Error in load(glm.RData) : object 'glm.RData' not found"
#I tried :
load(file='glm.RData') # no error was displayed
print(glm) # got an error:"Error in load(glm.RData) : object 'glm.RData' not found"
Any help will be great.
As per @user3710546's advice, I would avoid saving your model using the name glm
, as it'll mask (ie. block) the glm()
function, making it difficult for you to use it in your session.
save()
and load()
save()
is generally used to save a list of objects to a file, rather than a single object. The first argument to save()
is list
, 'A character vector containing the names of objects to be saved.' (Emphasis mine.) So you'd want to use it like this:
# On machine 1:
save(list = 'glm', file = '/path/to/glm.RData')
# On machine 2:
load(file = '/path/to/glm.RData')
Note that the file extensions are often case-sensitive: you saved to a file with the extension .RData
but loaded from one with the extension .Rdata
, which is different. This may explain why the file isn't found.
saveRDS()
and readRDS()
An alternative to using save()
and load
is to use saveRDS()
and readRDS()
, which are designed to be used with one object. They're used slightly differently:
# On machine 1
saveRDS(glm, file = '/path/to/glm.rds')
# On machine 2
glm = readRDS(file = '/path/to/glm.rds')
Note the .rds
file extension and the fact that readRDS()
isn't automatically put in the environment (it needs to be assigned to something).
If you just want the formula saved—that is, the actual text string—you can find it in glm$formula
, where glm
is the name of your object. It comes back as a formula
object, but you can convert it to a string with as.character(glm$formula)
, to then be written to a text file or whatever.
If, however, you want the model itself without the dataset it was created from (to cut down on disk space), have a look at this article , which discusses which parts of a glm
object can be safely deleted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.