Created
October 6, 2022 14:13
-
-
Save alexpkeil1/c27f31dd100da1a33e178e2ace62f192 to your computer and use it in GitHub Desktop.
Fix error in plotting qgcomp.cox.boot objects when using variable transformations (e.g. splines) on covariates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# scoping issue when using in-formula transformations | |
# example: spline basis functions | |
# problem: when including functions like `rms(x)` in a formula to put a spline | |
# function on 'x', plotting a qgcomp.cox.boot object yields an error that 'x' can't be found | |
# solution: explicitly create the spline basis functions as variables in a data.frame. Example follows. | |
library(qgcomp) | |
library(rms) | |
library(survival) | |
# testing data | |
set.seed(50) | |
N=200 | |
dat <- data.frame(time=(tmg <- pmin(.1,rweibull(N, 10, 0.1))), | |
d=1.0*(tmg<0.1), x1=runif(N), x2=runif(N), z=runif(N)) | |
expnms=paste0("x", 1:2) | |
# restricted cubic spline for Z - using the spline function in the formula | |
# using splines in the formula works for model fitting, but plotting it will fail | |
f_nlin1 = survival::Surv(time, d)~x1 + x2 + rcs(z, quantile(dat$z, c(.1, .5, .9), include.lowest=TRUE)) | |
set.seed(12312) | |
(fit_nlin1 <- qgcomp.cox.boot(f_nlin1, expnms = expnms, data = dat, B=10, MCsize=200)) | |
# plot(fit_nlin1) # error: Error in rcs(z) : object 'z' not found | |
# workaround: explicitly bring in the spline variables | |
zspl = unclass(rcs(dat$z, quantile(dat$z, c(.1, .5, .9), include.lowest=TRUE))) | |
colnames(zspl) <- paste0("zspl", 1:ncol(zspl)) # check the number of columns to be sure you have the formula correct | |
dat2 = cbind(dat, as.data.frame(zspl)) | |
f_nlin2 = survival::Surv(time, d)~x1 + x2 + zspl1 + zspl2 | |
# confirm that results are the same in a standard Cox model first | |
coxph(f_nlin1, data = dat2) | |
coxph(f_nlin2, data = dat2) | |
set.seed(12312) | |
(fit_nlin2 <- qgcomp.cox.boot(f_nlin2, expnms = expnms, data = dat2, B=10, MCsize=200)) | |
plot(fit_lin) # this works |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment