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

时间:2019-02-18 15:04:48

标签: r term cox-regression

我需要从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。是否有一个简单的函数或其他方法可以从模型术语中给我这个名字?

1 个答案:

答案 0 :(得分:1)

我不确定这对您特别需要执行的操作的效果如何。但这是一个开始

> 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])