Sebastian Gerdes
Sebastian Gerdes

Reputation: 166

Evaluate arguments when calling a function

Background: I am currently writing a function for a package that builds an survival and survminer. The function is supposed to be able to group survival curves that are provided by an argument

The package survminer seems to not handle the formula in the survfit very gracefully. I have already filed an issue to the survminer project. However, this might take some time. I am looking for a workaround.

Looking at the following code:

library('survival')
my_formula <- Surv(time, status) ~ x
survfit(eval(my_formula), data = aml)
## Call: survfit(formula = eval(my_formula), data = aml)
## 
##                  n events median 0.95LCL 0.95UCL
## x=Maintained    11      7     31      18      NA
## x=Nonmaintained 12     11     23       8      NA
survfit(Surv(time, status) ~ x, data = aml)
## Call: survfit(formula = Surv(time, status) ~ x, data = aml)
## 
##                  n events median 0.95LCL 0.95UCL
## x=Maintained    11      7     31      18      NA
## x=Nonmaintained 12     11     23       8      NA

Does anyone have an idea how to make the formula argument in the third line of the code evaluated in the call to survfit? The output should then be identical to the output of the fourth line of the code. I have tried survfit(eval(my_formula), data = aml) and similar things but they don't do the job.

Any help is greatly appreciated!

Thanks and best greetings, Sebastian

PS: Here the correspoding issue at the github project page of survminer: https://github.com/kassambara/survminer/issues/602

Upvotes: 0

Views: 44

Answers (1)

user2554330
user2554330

Reputation: 44788

You can do it using do.call:

library('survival')
my_formula <- Surv(time, status) ~ x
do.call(survfit, list(my_formula, data = quote(aml)))
#> Call: survfit(formula = Surv(time, status) ~ x, data = aml)
#> 
#>                  n events median 0.95LCL 0.95UCL
#> x=Maintained    11      7     31      18      NA
#> x=Nonmaintained 12     11     23       8      NA

Created on 2022-10-11 with reprex v2.0.2

You need to quote the data argument or the display will show all of its values instead of its name.

Upvotes: 2

Related Questions