1
votes

I'm trying to plot a Kaplan-Meier survival plot in R, but I'm having some trouble.

I'm quite new to R, so forgive my terrible code.

library(survival)
data_time = c(0.19,0.75,0.27,0.26,0.22,0.91,0.21,0.091,0.19,0.37,0.093,0.92,0.046,0.93,042)
data_event = c(1,1,1,1,0,0,1,1,0,0,0,1,1,1,0)
surv_object = Surv(time = data_time, event = data_event)
survfit(surv_object)

This of course gives me an error: "The survfit function requires a formula as its first argument".

I've split the data into two vectors, the first for the life-length, and the second for whether or not that specific data point was censored or not, with 0 meaning not censored, and 1 meaning censored.

I thought the Surv function was supposed to produce the formula required for the survfit function, with the default being the Kaplan-Meier.

1
It needs to be a formula. There are some examples in ?Survakrun
The Surv function just returns a special kind of matrix. The function in a formula is (believe it or not) the ~-character.IRTFM

1 Answers

3
votes

The survfit function, as the name suggests, serves to fit a survival model, i.e. predicting survival based on some variables. The "formula" is the non-linear y = f(x) model that is fitted, expressed as Surv(...) ~ x1 + ... + xn.

However, it is definitely possible to do a Kaplan-Meier survival plot without any predictors. Just fitting the model on a constant (i.e. 1) should do the trick. Then, I like to use the ggsurvplot function from the survminer package.

install.packages("survminer")
library(survminer)
library(survival)

data_time = c(0.19,0.75,0.27,0.26,0.22,0.91,0.21,0.091,0.19,0.37,0.093,0.92,0.046,0.93,0.42)
data_event = c(1,1,1,1,0,0,1,1,0,0,0,1,1,1,0)
surv_object = Surv(time = data_time, event = data_event)

# Regress on a constant
fit <- survfit(surv_object ~ 1)

# Plot the fit
ggsurvplot(fit, data.frame(time=data_time, event=data_event), conf.int=FALSE)

survival plot with ggsurvplot

Of course, the plot will be a lot more interesting if you're fitting some strata.

Note: I assume you missed a period in the last even time, and fixed it.