I am trying to fit many survival models using tidymodels, workflow, and purr. I can get this approach to work for other models, e.g., linear regression, but not survival. I have loaded the survival extension to parsnip.
Here is code to
- Generate a small dataset.
- Demonstrate that usual cox-ph works fine.
- Run linear regression with tidymodels and workflows and it works fine (models1).
- However, models2 and models3 result in error message: Error in `fit_xy()': !Models for censored regression must use the formula interface.
This message does not help me much. I suppose it has something to do with the in-line Surv() object but haven't been able to see how to construct this another way.
I realize that parsnip for survival may still be work-in-progress, but it is unclear to me if this has been implemented and should work or not. Appreciate any help, Thanks.
library(tidyverse)
library(tidymodels)
library(survival)
library(censored)
set.seed(1973)
df <- tibble(id = seq(1:1000))
df <- df %>% mutate( survtime = floor(100*rgamma(n=1000, shape =1 , rate=1)) ,
fail = runif(n=1000) >0.33 ,
a1 = runif(n=1000) >0.1,
a2 = runif(n=1000) >0.5)
head(df)
cox1 <- coxph(data = df, Surv(survtime, event=fail) ~a1)
summary(cox1)
cox2 <- coxph(data = df, Surv(survtime, event=fail) ~a2)
summary(cox2)
A <- c("a1", "a2")
models1 <- map(A,
~workflow() %>%
add_model(linear_reg()) %>%
add_formula(reformulate(.x, response = 'survtime')) %>%
fit(df)
)
models1
#not working
models2 <- map(A,
~workflow() %>%
add_model(proportional_hazards()) %>%
add_formula(reformulate(.x, response = 'Surv(survtime, event=fail)')) %>%
fit(df)
)
#not working
models3 <- map(A,
~workflow() %>%
add_model(proportional_hazards()) %>%
add_formula(as.formula(paste0('Surv(survtime, event=fail) ~ ', .x))) %>%
fit(df)
)
models3
EDITED to change variables X, x1, and x2 to A, a1, and a2 for clarity. Error message is the same:
Error in `fit_xy()': !Models for censored regression must use the formula interface.
However, problem may be version of R or packages. Error happens with version 4.1.2 with survival 3.4-0 parsnip 1.0.1
but code works on another system with R 4.2.2 parsnip 1.0.3 survival 3.3-1
Unfortunately, I am at sysadmin's mercy for updates so I did not check versioning and cannot easily troubleshoot.
Uppercase "X" instead of lower case "x" is the issue.
Your not the first to do this (I stared at it for a few minutes to see it) so don't feel bad.
However... this example is exactly why we have the
reprex
package. That would have told you the issue right away since it starts with a fresh session (and would show us the error message)Knowing's half the battle :-)
Created on 2023-01-06 with reprex v2.0.2