You can use predict
to get the predicted survival at any time and any level of covariates you wish. You haven't supplied your model or your data, so I will create a demo from the survival
package's built-in lung
data set.
library(survival)
df <- survival::lung[c(2, 3, 4, 5)]
df$time <- (df$time * 2) / 365
df$status <- df$status - 1
model <- coxph(Surv(time, status) ~ age + strata(sex), df)
To get predictions at ten years for both sexes at a range of ages, we create a little data frame with all the variables used in our model but set to the values we want (including status
, which is ignored, so we can set that to 0)
new_data <- data.frame(age = rep(50:90, 2), sex = rep(1:2, each = 41),
time = 10, status = 0)
Now we plug this new data into predict
with type = "survival"
and store it in our new data frame.
new_data$survival <- predict(model, newdata = new_data, type = "survival")
Now we can just plot the result. Here, I'll use ggplot
:
library(ggplot2)
ggplot(new_data, aes(age, survival, color = c("male", "female")[sex])) +
geom_line(size = 1.5) +
scale_color_manual(values = c("orangered", "deepskyblue3"), name = "Sex") +
scale_y_continuous(labels = scales::percent) +
labs(title = "10 year survival according to age") +
theme_minimal() +
theme(text = element_text(size = 16))

Created on 2022-03-10 by the reprex package (v2.0.1)