tidymodels / censored

Parsnip wrappers for survival models
https://censored.tidymodels.org/
Other
123 stars 12 forks source link

Make use of `data.frame = TRUE` option to `summary.survfit()` #327

Open hfrick opened 5 months ago

hfrick commented 5 months ago

With version 3.7-0, the survival packages offers a data.frame = TRUE option to summary.survfit(). This means we can use that directly instead of doing the conversion to a data frame ourselves. We'll still need to get it into a nested tibble eventually and take care of rows in new_data with missing values but it would simplify the code nonetheless.

library(survival)

pred_time <- c(1022, -Inf, 0, Inf, 1022, -Inf)

# for coxph
lung_pred <- tidyr::drop_na(lung)
mod <- coxph(Surv(time, status) ~ ., data = lung)
surv_fit <- survfit(mod, newdata = lung_pred[1:2, ])

summary(surv_fit, times = pred_time, extend = TRUE, data.frame = TRUE)
#>    time n.risk n.event n.censor        surv   cumhaz     std.err  std.chaz
#> 1  1022      1       0        1 0.116689709 2.148237 0.067770013 0.5807711
#> 2  -Inf    167       0        0 1.000000000 0.000000 0.000000000 0.0000000
#> 3     0    167       0        0 1.000000000 0.000000 0.000000000 0.0000000
#> 4   Inf      0       0        1 0.116689709 2.148237 0.067770013 0.5807711
#> 5  1022      1       0        1 0.116689709 2.148237 0.067770013 0.5807711
#> 6  -Inf    167       0        0 1.000000000 0.000000 0.000000000 0.0000000
#> 7  1022      1       0        1 0.001577772 6.451741 0.002981764 1.8898571
#> 8  -Inf    167       0        0 1.000000000 0.000000 0.000000000 0.0000000
#> 9     0    167       0        0 1.000000000 0.000000 0.000000000 0.0000000
#> 10  Inf      0       0        1 0.001577772 6.451741 0.002981764 1.8898571
#> 11 1022      1       0        1 0.001577772 6.451741 0.002981764 1.8898571
#> 12 -Inf    167       0        0 1.000000000 0.000000 0.000000000 0.0000000
#>           lower      upper data
#> 1  3.738344e-02 0.36423848    1
#> 2  1.000000e+00 1.00000000    1
#> 3  1.000000e+00 1.00000000    1
#> 4  3.738344e-02 0.36423848    1
#> 5  3.738344e-02 0.36423848    1
#> 6  1.000000e+00 1.00000000    1
#> 7  3.885036e-05 0.06407573    2
#> 8  1.000000e+00 1.00000000    2
#> 9  1.000000e+00 1.00000000    2
#> 10 3.885036e-05 0.06407573    2
#> 11 3.885036e-05 0.06407573    2
#> 12 1.000000e+00 1.00000000    2

Created on 2024-06-12 with reprex v2.1.0