4
votes

I am trying to plot Kaplan-Meyer curve using ggsurvplot from survminer package. I'm unable to plot it when I pass a survfit object saved in a list.

Let me use lung dataset as a example. Everything works below:

library("survival")
library("survminer")
fit <- survfit(Surv(time, status) ~ sex, data = lung)
ggsurvplot(fit,
          conf.int = TRUE,
          risk.table.col = "strata", 
          palette = c("#E7B800", "#2E9FDF"),
          xlim = c(0, 600))

Now I do survfit on two variables and save the model result in a list. Then tried to make KM plot with ggsurvplot.

vars <- c('sex', 'ph.ecog')
l<- map (vars, ~survfit(Surv(time, status)~ get(.x),data = lung ))
l<- set_names(l, vars)
ggsurvplot(l$sex,
          conf.int = TRUE,
          risk.table.col = "strata", 
          palette = c("#E7B800", "#2E9FDF"),
          xlim = c(0, 600))

I got error message like this:

Error in eval(inp, data, env) : object '.x' not found

Does someone know why? How can I fix this problem? Thanks a lot!

1

1 Answers

0
votes

First one would need to load the package or packages needed. I suppose these days many users think that running R means that everyone is presumed to have the tidyverse in place, but that is NOT true.

 library(tidyverse)
 # run both your code segments, since you will need a small piece of first one
str(l$sex)
List of 14
 $ n        : int [1:2] 138 90
 $ time     : num [1:206] 11 12 13 15 26 30 31 53 54 59 ...
 $ n.risk   : num [1:206] 138 135 134 132 131 130 129 128 126 125 ...
 $ n.event  : num [1:206] 3 1 2 1 1 1 1 2 1 1 ...
 $ n.censor : num [1:206] 0 0 0 0 0 0 0 0 0 0 ...
 $ surv     : num [1:206] 0.978 0.971 0.957 0.949 0.942 ...
 $ type     : chr "right"
 $ strata   : Named int [1:2] 119 87
  ..- attr(*, "names")= chr [1:2] "get(.x)=1" "get(.x)=2"
 $ std.err  : num [1:206] 0.0127 0.0147 0.0181 0.0197 0.0211 ...
 $ upper    : num [1:206] 1 0.999 0.991 0.987 0.982 ...
 $ lower    : num [1:206] 0.954 0.943 0.923 0.913 0.904 ...
 $ conf.type: chr "log"
 $ conf.int : num 0.95
 $ call     : language survfit(formula = Surv(time, status) ~ get(.x), data = lung)
 - attr(*, "class")= chr "survfit"

So when you see that strata "names"-attribute, it's got a get(-call in it and that appears to choke the logic of ggsurvplot. Use attr<- to replace it with something more informative (and less-"language-y").

attr(l[['sex']][['strata']], "names") <- c("sex=1", "sex=2")

That expression is in the "call"-leaf as well, so you will need to replace it with something more tractable. I think that's easy to do by replacing it with the "call" leaf from the firstfit`-object yoiu made:

l$sex$call <- fit$call
ggsurvplot(l$sex,
          conf.int = TRUE,
          risk.table.col = "strata", 
          palette = c("#E7B800", "#2E9FDF"),
          xlim = c(0, 600))

enter image description here