从cox模型术语中提取失败变量的名称

问题描述 投票:2回答:1

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

r term cox-regression
1个回答
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])
© www.soinside.com 2019 - 2024. All rights reserved.