admin管理员组

文章数量:1315985

I'd like to write a function that allows me to create a formula object using quoted arguments, and then pipe that formula object through tbl_survfit. This would allow me to easily change parts of the formula when calling my function or using it with purrr::map.

I get an error when I try to pipe a formula object through tbl_survfit (reprex below). Where am I going wrong? Thanks in advance for any advice/help!

# load packages
library(reprex)
library(gtsummary)
library(ggsurvfit)
#> Loading required package: ggplot2

# Pipe a ggsurvfit::survfit2 call through tbl_survfit
ggsurvfit::survfit2(Surv(ttdeath, death) ~ 1, data = trial) %>% 
  tbl_survfit(probs = 0.5)

# Pipe a formula object through tbl_survfit. I expected the output to match the output of the code above 
"Surv(ttdeath, death) ~ 1" %>% 
  as.formula() %>% 
  ggsurvfit::survfit2(data = trial) %>% 
  tbl_survfit(probs = 0.5)
#> Error in `rlang::f_rhs()`:
#> ! `x` must be a formula

# Example function that would pipe a formula object through tbl_survfit
myfun <- function(strata = NULL){
  if(!is.null(strata)){
    formula <- paste0("Surv(ttdeath, death) ~ 1") %>% 
      as.formula()
  }
  else{
    formula <- paste0("Surv(ttdeath, death) ~ ", strata) %>% 
      as.formula()
  }
  formula %>% 
    ggsurvfit::survfit2(data = trial) %>% 
    tbl_survfit(probs = 0.5)
}

# call function with no strata arg
myfun()
#> Error in str2lang(x): <text>:2:0: unexpected end of input
#> 1: Surv(ttdeath, death) ~ 
#>    ^
# call function with strata arg
myfun(strata = "trt")
#> Error in `rlang::f_rhs()`:
#> ! `x` must be a formula

<sup>Created on 2025-01-29 with reprex v2.1.1</sup>

enter image description here Screenshot of output from piping a ggsurvfit::survfit2 call through tbl_survfit

本文标签: rCan I pass a formula object through tblsurvfitStack Overflow