Daniel D. Sjoberg
Daniel D. Sjoberg

Reputation: 11650

Error wrapping `survival::survfit()` in another function

I've written a function that wraps the survival::survfit() function. It works in most cases (i.e. just using the formula= and data= arguments), but fails when adding the cluster= argument.

Is there a way to make this work? I need to keep my wrapping functions generic and pass arguments to survival::survfit() via ....

Thank you!

library(survival)

survfit_wrapper <- function(formula, ...) {
  survival::survfit(formula = formula, ...)
}

# works with the formula and data arguments
survfit_wrapper(
  formula = Surv(time, status) ~ 1,
  data = lung
)
#> Call: survfit(formula = formula, data = ..1)
#> 
#>        n events median 0.95LCL 0.95UCL
#> [1,] 228    165    310     285     363

# ERROR with the cluster argument
survfit_wrapper(
  formula = Surv(time, status) ~ 1,
  data = lung,
  cluster = pat.karno
)
#> Error in eval(extras, data, env): ..2 used in an incorrect context, no ... to look in

# But works with a direct call to `survival::survfit()`
survfit(
  formula = Surv(time, status) ~ 1,
  data = lung,
  cluster = pat.karno
)
#> Call: survfit(formula = Surv(time, status) ~ 1, data = lung, cluster = pat.karno)
#> 
#>    3 observations deleted due to missingness 
#>        n events median 0.95LCL 0.95UCL
#> [1,] 225    162    320     239     394

Created on 2022-09-21 with reprex v2.0.2

Upvotes: 1

Views: 211

Answers (1)

Daniel D. Sjoberg
Daniel D. Sjoberg

Reputation: 11650

Not sure why the original code wasn't working, but I did find this solution:

survfit_wrapper <- function(formula, ...) {
  # solution taken from https://adv-r.hadley.nz/evaluation.html#match.call
  call <- match.call(survival::survfit, expand.dots = TRUE)
  call[[1]] <- quote(survival::survfit)
  eval(call, parent.frame())
}

Upvotes: 0

Related Questions