0

请考虑以下几点:

要创建生存曲线,可以利用包的survfit功能survival

我的目标是编写一个(除其他外)创建这样一条曲线的函数,但该函数应该与data.frames列名也不同的不同函数一起使用。此外,分组变量将取决于各自的数据集。

我设法将不同的名称传递给函数,但为and函数data.frame提供列名对我不起作用。survfitSurv

任何帮助是极大的赞赏。

在我看来,这与简单地将列名传递给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 包(v0.2.0)于 2018 年 7 月 5 日创建。

4

1 回答 1

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)
}
于 2018-07-05T14:18:37.423 回答