问题描述
从 ggsurvplot 文档中,我可以对 ggplot 对象进行分面,如下所示。
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Facet ggsurvplot() output by
# a combination of factors
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Fit (complexe) survival curves
#++++++++++++++++++++++++++++++++++++
require("survival")
fit3 <- survfit( Surv(time,status) ~ sex + rx + adhere,data = colon )
# Visualize: plot survival curves by sex and facet by rx and adhere
#++++++++++++++++++++++++++++++++++++
ggsurv <- ggsurvplot(fit3,conf.int = TRUE)
ggsurv$plot +theme_bw() + facet_grid(rx ~ adhere)
现在如果我要使用 survreg
来拟合 Weibull 模型,我必须使用 ggsurvplot_df
如下。
我面临的挑战是 ggsurvplot
和 ggsurvplot_df
之间的不一致,尽管两者都建立在 ggplot
之上。
有没有办法将 ggsurvplot_df
对象分面为 ggsurvplot
对象?
# Weibull model
wbmod <- survreg(Surv(time,data = colon)
summary(colon)
# Imaginary patients
newdat <- expand.grid(
rx = levels(colon$rx),adhere = unique(colon$adhere),sex = unique(colon$sex))
newdat
# Compute survival curves
surv <- seq(.99,.01,by = -.01)
t <- predict(wbmod,type = 'quantile',p = 1-surv,newdata = newdat)
# How many rows and columns does t have?
dim(t)
# Use cbind() to combine the information in newdat with t
surv_wbmod_wide <- cbind(newdat,t)
# Use melt() to bring the data.frame to long format
library(reshape2)
surv_wbmod <- melt(surv_wbmod_wide,id.vars = c('rx','adhere','sex'),variable.name = 'surv_id',value.name = 'time')
dim(surv_wbmod)
# Use surv_wbmod$surv_id to add the correct survival probabilities surv
surv_wbmod$surv <- surv[as.numeric(surv_wbmod$surv_id)]
# Add columns upper,lower,std.err,and strata to the data.frame
surv_wbmod[,c("upper","lower","std.err","strata")] <- NA
# Take a look at the structure of the object
str(surv_wbmod)
# Plot the survival curves
ggsurvplot_df(surv_wbmod,surv.geom = geom_line,linetype = 'rx',color = 'adhere',legend.title = NULL)