'Extract name of failure variable from cox model terms
I need to extract the name of the failure variable from a description of a Cox model in R. Note I don't have the object itself, I have terms(coxfit) that has been returned from a third party function. To give a reproducible example - suppose this is the model built within a third party program:
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)
So after this I just have access to the terms:
> 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"
What I want to do is extract the name of the failure variable - i.e. in this case the name is: status. Is there a simple function or some other way that will give me this name from the model terms?
Solution 1:[1]
I am not sure how well this will work for what you specifically need to do. But it is a start
> 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"
So, in sum, you could do something like this
var_name <- stri_extract_last_words(as.character(Terms)[2])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew |
