I am trying to make a KM curve function, however, I am not sure where I am going wrong.
Edit: I have changed the code to see if it will work with the publically available ovarian data set https://stat.ethz.ch/R-manual/R-devel/library/survival/html/ovarian.html
library(tidyverse)
library(ggplot)
library(survival)
library(survminer)
km_curve <- function(df, tm, ev, predictor) {
surv_object <- Surv(time = df$tm, event = df$ev)
fit1 <- survfit(surv_object ~ predictor, data = df)
ggsurvplot(fit1, data = df, pval = TRUE, xlab = "Months")
}
The above code works perfectly well If I replace all df, tm, ev, and predictor with the actual names.
I also tried this
km_curve <- function(df, tm, ev, predictor) {
surv_object <- Surv(time = df[,tm], event = df[,ev])
fit1 <- survfit(surv_object ~ predictor, data = df)
ggsurvplot(fit1, data = df, pval = TRUE, xlab = "Months")
}
I have also tried
km_curve <- function(df, tm, ev, predictor) {
tim <- df %>%
select(tm)
even <- df %>%
select(ev)
surv_object <- Surv(time = tim, event = even)
fit1 <- survfit(surv_object ~ predictor, data = df)
ggsurvplot(fit1, data = df, pval = TRUE, xlab = "Months")
}
km_curve(df = ovarian,
tm = futime,
ev = fustat,
predictor = rx)
It keeps giving me error messages that pf_time_months not found. Even though it is a column in my data frame I specify.
This does not work either
library(tidyverse)
library(survival)
library(survminer)
ovarian
km_graph<-function(t, e, var, df, xaxis = "Months"){
surv_object <- Surv(time = t, event =e)
fit1<- survfit(surv_object ~ var, data = df)
kmgraph<-ggsurvplot(fit1, data = df, pval = TRUE, xaxis = "Months", risk.table = T)
kmgraph$table <- ggrisktable(fit1,
data = df,
color = "strata",
y.text = T, ylab = "", xlab = "",
tables.theme = theme_cleantable(),
)
return(kmgraph)
}
km_graph(t = ovarian$futime, e =ovarian$fustat, var = rx, df = ovarian)
Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class ‘"function"’ to a data.frame
My guess (I have to guess since you don't provide a reproducible code) is that
pfs_time_monthsand others are the names of some columns ofdf. That's why that does not work. You can pass them as character strings if you use this function: