For prediction need, I want to save a coxph
or cph
model to be able use it in my function.
So my question is how to save the all coxph
(or cph
) object and then how to load it when needed?
The object will be used in the predictCox
function (library riskRegression
)
library(survival)
library(data.table)
library(riskRegression)
#### generate data ####
set.seed(10)
d <- sampleData(40,outcome="survival") ## training dataset
nd <- sampleData(4,outcome="survival") ## validation dataset
d$time <- round(d$time,1) ## create tied events
fit <- coxph(Surv(time,event)~X1 + X6,
data=d, ties="breslow", x = TRUE, y = TRUE)
## compute individual specific cumulative hazard and survival probabilities
fit.pred <- predictCox(fit, newdata=nd, times=3, se = TRUE, band = TRUE)
You can use the save
function to store R objects in a file. If you want to store a single R object you should use the extension .rds
and saveRDS
function. On other hand, if you want to store several objects you should use the .Rdata
file extension.
Examples
Single object:
saveRDS(model, file="model.rds")
model <- readRDS(file="model.rds")
In this case the object name is not stored, so you need to use the readRDS
function and assign <-
the object to a new variable in your environment.
Multiple objects:
save(model1, model2, df, file = "models_and_data.RData")
If you want to save all objects currently in your work environment you can call save.image
instead:
save.image(file="project_image.RData")
In both cases all objects are saved with their original name, so you can load them into your environment with the load
function without assigning new names:
load(file="models_and_data.RData")
Beware that some implementations of coxph
make a copy of the data to model object (check if your model object has model
in its structure, i.e model$model
). If you are working with sensitive data and need to export models, make sure you are not exporting sensitive data hidden in the object.
Source: https://stat.ethz.ch/R-manual/R-devel/library/base/html/readRDS.html