从 cox 模型项中提取故障变量的名称

Extract name of failure variable from cox model terms

我需要从 R 中 Cox 模型的描述中提取失败变量的名称。请注意,我没有对象本身,我有 terms(coxfit) 从第三方返回的功能。举一个可重现的例子——假设这是在第三方程序中构建的模型:

library(survival)

test1 <- list(time=c(4,3,1,1,2,2,3), 
              status=c(1,1,1,0,1,1,0), 
              x=c(0,2,1,1,1,0,0), 
              sex=c(0,0,0,0,1,1,1)) 

coxfit <- coxph(Surv(time, status) ~ x + strata(sex), test1)
# Third party program does a bunch of other stuff
# Returns as part of its output the terms for coxfit:
Terms <- terms(coxfit) 

所以在这之后我只能访问条款:

> Terms
Surv(time, status) ~ x + strata(sex)
attr(,"variables")
list(Surv(time, status), x, strata(sex))
attr(,"factors")
                   x strata(sex)
Surv(time, status) 0           0
x                  1           0
strata(sex)        0           1
attr(,"term.labels")
[1] "x"           "strata(sex)"
attr(,"specials")
attr(,"specials")$strata
[1] 3

attr(,"specials")$cluster
NULL

attr(,"specials")$tt
NULL

attr(,"order")
[1] 1 1
attr(,"intercept")
[1] 1
attr(,"response")
[1] 1
attr(,".Environment")
<environment: R_GlobalEnv>
attr(,"predvars")
list(Surv(time, status), x, strata(sex))
attr(,"dataClasses")
Surv(time, status)                  x        strata(sex) 
       "nmatrix.2"          "numeric"           "factor" 

我想做的是提取失败变量的名称 - 即在本例中名称是:status。有没有简单的函数或其他方法可以根据模型术语给我这个名字?

我不确定这对您具体需要做的事情的效果如何。但这是一个开始

> library(stringi)
> 
> # Convert the formula to character
> terms2 <- as.character(Terms)
> 
> terms2
[1] "~"                  "Surv(time, status)" "x + strata(sex)"   
> 
> # Second element has the variable name of interest
> terms2[2]
[1] "Surv(time, status)"
> 
> # Extract the last word (also removes punctuation)
> stri_extract_last_words(terms2[2])
[1] "status"

所以,总而言之,您可以这样做

var_name <- stri_extract_last_words(as.character(Terms)[2])