请考虑以下内容:
要创建生存曲线,可以使用survfit
包的survival
函数。
我的目标是编写一个(除其他外)创建这种曲线的函数,但是该函数应该与列名也不同的data.frames
一起使用。另外,分组变量将取决于相应的数据集。
我设法将不同的data.frame
名称传递给该函数,但为survfit
和Surv
函数提供列名对我不起作用。
非常感谢您的帮助。
我认为,这与将data.frame
列名简单地传递给此处讨论的函数是一个不同的问题:Pass a data.frame column name to a function
# required libraries
library(survival)
library(flexsurv)
#### Examples that work without own function ===================================
# survfit wit lung data
survfit(Surv(time = time, event = status) ~ 1, data = lung)
#> Call: survfit(formula = Surv(time = time, event = status) ~ 1, data = lung)
#>
#> n events median 0.95LCL 0.95UCL
#> 228 165 310 285 363
survfit(Surv(time = time, event = status) ~ sex, data = lung)
#> Call: survfit(formula = Surv(time = time, event = status) ~ sex, data = lung)
#>
#> n events median 0.95LCL 0.95UCL
#> sex=1 138 112 270 212 310
#> sex=2 90 53 426 348 550
# survfit with bc data
survfit(Surv(time = rectime, event = censrec) ~ 1, data = bc)
#> Call: survfit(formula = Surv(time = rectime, event = censrec) ~ 1,
#> data = bc)
#>
#> n events median 0.95LCL 0.95UCL
#> 686 299 1807 1587 2030
# Create variable function that takes on data specific arguments
SurvFun <- function(fun.time, fun.event, grouping = 1, fun.dat){
survfit(Surv(time = fun.time, event = fun.event) ~ grouping, data = fun.dat)
}
#### Own function that doesn't work ============================================
# This should work for data = lung
SurvFun(fun.time = time, fun.event = status, grouping = 1, fun.dat = lung)
#> Error in Surv(time = fun.time, event = fun.event): Time variable is not numeric
由reprex package(v0.2.0)于2018-07-05创建。
答案 0 :(得分:2)
当列名没有用引号引起来时,它们将作为符号传递。与简单变量相比,传递符号要困难得多。这也适用于公式。您需要执行一些元编程才能使其正常工作。这是重新编写功能以使其正常工作的一种方法
SurvFun <- function(fun.time, fun.event, grouping = 1, fun.dat) {
params <- list(fun.time = substitute(fun.time),
fun.event = substitute(fun.event),
grouping = substitute(grouping),
fun.dat = substitute(fun.data))
expr <- substitute(survfit(Surv(time = fun.time, event = fun.event) ~ grouping,
data = fun.dat), params)
eval.parent(expr)
}