I am trying to create ggsurvplot objects using a list of exposure variables using functions
My code is working for the first part to create KM models (survfit() objects)
library(survival)
anxiety_df <- data.frame(
id = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
time_months = c(0, 2, 25, 15, 38, 4, 6, 12, 22, 9),
outcome = c(0, 0, 1, 0, 0, 1, 0, 1, 0, 1),
anxiety = c(0, 1, 1, 0, 1, 1, 0, 0, 0, 1)
)
adhd_df <- data.frame(
id = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
time_months = c(0, 2, 25, 15, 38, 4, 6, 12, 22, 9),
outcome = c(0, 0, 1, 0, 0, 1, 0, 1, 0, 1),
adhd= c(0, 1, 1, 0, 1, 1, 0, 0, 0, 1)
)
exposures <- c("anxiety", "adhd", "ocd", "ptsd")
create_model <- function(cox_df, exposure_var) {
km.model <- survfit(Surv(time_months, outcome) ~ get(exposure_var), cox_df)
return(km.model)
}
model1 <- create_model(anxiety_df, exposures[1])
model2 <- create_model(adhd_df, exposures[2])
But it gives an error when I add the ggsurvplot code:
library(survival)
library(survminer)
exposures <- c("anxiety", "adhd", "ocd", "ptsd")
create_model <- function(cox_df, exposure_var) {
km.model <- survfit(Surv(time_months, outcome) ~ get(exposure_var), cox_df)
plot<-ggsurvplot(km.model, cox_df, fun="event")
return(plot)
}
model1 <- create_model(anxiety_df, exposures[1])
model2 <- create_model(adhd_df, exposures[2])
Error Message: Error in FUN(X[[i]], ...) : object 'exposure_var' not found