R: Tibble vs ggplot2 (trazando gráficos)

Nov 27 2020

Estoy tratando de seguir un tutorial en R (https://rviews.rstudio.com/2017/09/25/survival-analysis-with-r/La computadora que estoy usando para el trabajo no tiene un puerto USB o conexión a Internet, solo tiene R con algunas bibliotecas instaladas. Mi computadora de trabajo tiene "survival, ranger, ggplot2 y dplyr". Sin embargo, no tiene "ggfortify". Estoy tratando de averiguar cómo trazar los gráficos del tutorial sin 'ggfortify'. Aquí está el código que estoy usando a continuación:

  #load libraries
    library(survival)
    library(ranger)
    library(ggplot2)
    library(dplyr)
    
#load data
data(veteran)
head(veteran)

#Part 1 : works
# Kaplan Meier Survival Curve
km <- with(veteran, Surv(time, status))
km_fit <- survfit(Surv(time, status) ~ 1, data=veteran)

#plot(km_fit, xlab="Days", main = 'Kaplan Meyer Plot') #base graphics is always ready

tibble(time = km_fit$time, surv = km_fit$surv, 
       min = km_fit$lower, max = km_fit$upper) %>% 
  ggplot(aes(x = time)) +
  geom_line(aes(y = surv)) +
  geom_ribbon(aes(ymin = min, ymax = max), alpha = 0.3)

Sin embargo, no puedo hacer que esto funcione:

#Part 2: does not work


km_trt_fit <- survfit(Surv(time, status) ~ trt, data=veteran)



tibble(time = km_trt_fit$time, surv = km_trt_fit$surv, 
       min = km_trt_fit$lower, max = km_trt_fit$upper) %>% 
    ggplot(aes(x = time, group = factor(veteran$trt), colour = factor(veteran$trt), fill = factor(veteran$trt))) +
    geom_line(aes(y = surv)) +
    geom_ribbon(aes(ymin = min, ymax = max), alpha = 0.3)


Error: Aesthetics must be either length 1 or the same as the data (114): group, colour and fill

O esto para que funcione:
#Parte 3: no funciona

vet <- mutate(veteran, AG = ifelse((age < 60), "LT60", "OV60"),
              AG = factor(AG),
              trt = factor(trt,labels=c("standard","test")),
              prior = factor(prior,labels=c("N0","Yes")))

aa_fit <-aareg(Surv(time, status) ~ trt + celltype +
                 karno + diagtime + age + prior , 
                 data = vet)

tibble(time = aa_fit$time, surv = aa_fit$surv, min = aa_fit$lower, max = aa_fit$upper) %>% 
  ggplot(aes(x = time)) +
  geom_line(aes(y = surv)) +
  geom_ribbon(aes(ymin = min, ymax = max), alpha = 0.3)

Error: geom_line requires the following missing aesthetics: y

¿Puede alguien ayudarme a corregirlos?

Gracias ( Publicación anterior: R: trazando gráficos (ggplot vs autoplot) )

Respuestas

1 jakub Nov 27 2020 at 21:20

¡Tendrás que hacer un trabajo de detective!

Hoy tengo tiempo para la parte 2. Entonces: resulta que la información sobre los estratos está contenida en el elemento km_trt_fit$strata. Se parece a esto:

km_trt_fit <- survfit(Surv(time, status) ~ trt, data=veteran)

km_trt_fit$strata

#> trt=1 trt=2 
#>    61    53

Esto le dice que hay 61 elementos de trt=1y 53 elementos de trt=2. No sé por qué estos no suman 137 (el número de filas veteran) pero supongo que así es como survfit()funciona. También es la razón por la que recibe el error, porque los datos del modelo resultante tienen un número de filas diferente al del marco de datos original, que está tratando de incluir mediante el uso veteran$trt.

Mi solución: cree un vector stratacon 61 y 53 elementos de trt=1y trt=2respectivamente:

strata = km_trt_fit$strata
strata = rep(names(strata), times = strata)

Incluya eso en sus datos de entrada:

tibble(time = km_trt_fit$time, surv = km_trt_fit$surv,
       min  = km_trt_fit$lower, max = km_trt_fit$upper,
       trt  = factor(strata)) %>%
  ggplot(aes(x = time, colour = trt, fill = trt)) +
  geom_line(aes(y = surv)) +
  geom_ribbon(aes(ymin = min, ymax = max), alpha = 0.3)

El resultado es bastante parecido al que tiene el tutorial.

No estoy demasiado familiarizado con ggfortify, pero su trabajo probablemente sea hacer algo similar para usted automágicamente. En su ausencia, tendrá que investigar las estructuras producidas por las funciones del modelo y extraer los datos manualmente como lo hice anteriormente.