survival icon indicating copy to clipboard operation
survival copied to clipboard

Error in making predictions when there is factor by strata interaction

Open bdeonovic opened this issue 11 months ago • 0 comments

I get the following error when I try to use predict on a coxph model where there is a factor by strata interaction.

Error in newx - xmeans[match(newstrat, row.names(xmeans)), ] : 
  non-conformable arrays

See below for MWE:

library(survival)

set.seed(123)
n <- 1000
z <- factor(sample(LETTERS[1:2], n, replace = TRUE, prob = c(0.6, 0.4)))
x <- sample(0:1, n, replace = TRUE, prob = c(0.3, 0.7))
xF <- factor(x)
cens <- 15 * runif(n)
h <- .02 * exp(0.8 * (z == "A") * (x == 1) + 1.6 * (z == "B") * (x == 1))
dt <- -log(runif(n)) / h
e <- ifelse(dt <= cens, 1, 0)
dt <- pmin(dt, cens)
df <- data.frame(dt, e, x, z)

m <- coxph(Surv(dt, e) ~ x * strata(z), data = df)
predict(m, newdata = df ) ## no problem if x is treated as continuous variable that takes on 0 or 1

m <- coxph(Surv(dt, e) ~ xF * strata(z), data = df)
predict(m, newdata = df) ## problem, although the model fit coefficients are the same

EDIT: alternatively I discovered if you can model it like this

m <- coxph(Surv(dt, e) ~ xF * z + strata(z), data = df)
predict(m, newdata = df) ## No problem, although there is a redundant coefficient which is set to NA

bdeonovic avatar Jan 24 '25 21:01 bdeonovic