I am trying to find a way to make a forest plot of hazard ratios from a Cox-PH model when one of the model variables needs to be stratified. For a non-stratified model, the ggforest()
function is excellent. Running some example code
library(survival)
library(survminer)
model <- coxph(Surv(time, status) ~ sex + rx + adhere,
data = colon )
ggforest(model)
colon <- within(colon, {
sex <- factor(sex, labels = c("female", "male"))
differ <- factor(differ, labels = c("well", "moderate", "poor"))
extent <- factor(extent, labels = c("submuc.", "muscle", "serosa", "contig."))
})
bigmodel <-
coxph(Surv(time, status) ~ sex + rx + adhere + differ + extent + node4,
data = colon )
ggforest(bigmodel)
produces this graph
However if I have to correct for non-proportionality with stratification
stratamodel <- coxph(Surv(time, status) ~ sex + strata(rx) + adhere + differ + extent + node4,
data = colon )
ggforest(stratamodel)
The following error message appears:
"Error in
[.data.frame
(data, , var) : undefined columns selected
In addition: Warning message:
In .get_data(model, data = data) : The
data
argument is not provided. Data will be extracted from model fit."
Any suggestions for how to get the information that ggforest needs from the strata model so that it can produce a plot? Thanks for your help!
I gather that the desired forest plot is one that simply skips the stratified RX variable in the model's formula. If so, we can simply insert an if clause inside, to ignore formula parts that don't correspond exactly to column names in the data (e.g. "strata(rx)" is not a column name).
Approach 1
If you are comfortable with R sufficiently to modify functions, run
trace(ggforest, edit = TRUE)
and replace theallTerms <- lapply(...)
(around lines 10-25) in the pop-up window with the following version:The modification will not persist to subsequent R sessions. If you want to reverse the modification within the current session, simply run
untrace(ggforest)
.Approach 2
If you prefer to have a permanently modified version of the function for future use / don't want to muck around with a library's function, save the function below:
It's a snapshot of the
ggforest
function as it currently stands, with the same modification as above. If the package's creator makes modifications to the package in the future, this can break or become outdated. But for now,ggforest2(stratamodel)
will yield the same result as Approach 1.