简体   繁体   中英

issues using survminer::ggsurvplot to plot many survival curves programmatically in r

I can plot a single Kaplan-Meier plot like below with ggsurvplot:

library(survminer)
library(survival)
fit1 = survfit(Surv(time, status) ~ sex, data = lung)
ggsurvplot(fit1, data = lung)

However, I need to plot many KM plot programmatically. I need to pass different variables as strings. I tried below.

fml = as.formula(paste('Surv(time, status)~', 'sex'))
fit2 = survfit(fml, data = lung)
ggsurvplot(fit2, data = lung)

surprisingly, this does not work. I got the error message below:

Error: object of type 'symbol' is not subsettable

I don't know why this happens. Does anyone know how to fix this? Thanks a lot.

As suggested at the link in Aidan's comment , you need to use the function survminer::surv_fit() , which is a wrapper around survival::survfit() . So, in your example,

library(survminer)
library(survival)
 # lung is distributed as an object, survival::lung
fit1 = surv_fit(Surv(time, status) ~ sex, data = lung)
ggsurvplot(fit1, data = lung)

The output from surv_fit(object.formula) can then be plotted

fml = as.formula(paste('Surv(time, status)~', 'sex'))
fit2 = surv_fit(fml, data = lung)
ggsurvplot(fit2, data = lung)

In the surv_fit help page it also shows how to fit a list of formulae.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM