0

I am trying to calculate a survival function over multiple variables, one of which is fu_time_PJP and fu_status_PJP. Here is the function, which works great under those paramaters:

km_time <- survfit(Surv(time = fu_time_PJP, 
                        event = fu_status_PJP) ~ prophied, 
                   data = df_ptm)

km_time
# Call: survfit(formula = Surv(time = fu_time_PJP, event = fu_status_PJP) ~ 
#     prophied, data = df_ptm)
#              n events median 0.95LCL 0.95UCL
# prophied=0 909      6     NA      NA      NA
# prophied=1 535      4     NA      NA      NA

I would like to write a custom function such that I can pass many variables into the same function, as such, but am getting an error:

km_fun <- function(x) {
  
  y <- paste0("fu_time_", x)
  z <- paste0("fu_status_", x)
  
  # Generate survival object
  km_time <- survfit(Surv(time = y, 
                          event = z) ~ prophied, 
                     data = df_ptm)
} 

km_fun("PJP") 
# Error in Surv(time = y, event = z) : Time variable is not numeric

I think the problem is that my pasted object (y and z) are not being read in the environment or proprly quoted. I've tried everyting, including as.name, as.function, {{}}, enquo, etc.

Help anyone?!?

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    You can use `paste()` to build your formula using your string values, and then use `as.formula` to turn it into a "real" formula. That includes the part before and after the `~`. Something like `km_time <- survfit(as.formula(paste("Surv(time = ",y,", event = ",z,") ~ prophied")), data = df_ptm)` (it would be easier to test if you provided a reproducible example we could use for testing) – MrFlick Jul 13 '23 at 16:33
  • *Ugh amazing thank you so much perfect. – Michael Putman Jul 13 '23 at 17:13
  • *Ugh amazing thank you so much perfect. – Michael Putman Jul 13 '23 at 17:13

0 Answers0