r - 从 cox 模型项中提取故障变量的名称
问题描述
我需要从 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])
推荐阅读
- html - Refused to load * because it appears in neither the img-src directive nor the default-src directive of the Content Security Policy
- c++ - How to call a method from a different class (area of rectangle)
- javascript - 如何在滚动的某些部分停止固定的背景附件图像
- amazon-web-services - AWS 如何释放 /dev/nvme1n1p1 和 /dev/loop# 处理“设备上没有剩余空间”
- redis - 如何检查redis master上当前打开的连接
- c++ - Qt curllib 无法添加
- stl - MAX_SIZE OF SET
- linux-kernel - rootkit 如何隐藏进程?
- java - Spring 安全 JWT
- python - 检索列中每个日期的出现次数