rstanarm
rstanarm copied to clipboard
posterior_epred fails for stan_clogit model with rms::rcs splines when newdata has only one value for spline covariate
Summary:
After fitting a stan_clogit
model in which two covariates are modelled with restricted cubic splines, posterior_epred
fails when trying to find conditional effects of one of these covariates if they other is fixed at one value.
Description:
I'm fitting a conditional logistic regression to a data set in which each stratum has 1 case and 5 controls, mathed on date of birth +/- 180 days. I use restricted cubic splines for the most interesting continuous covariates; a few categorical covariates are encoded as factors in the data input. When using the posterior_epred function to get conditional effects I've encountered two problems. I've opened an issue for one here; this issue addresses other one: in a model with two covariates modelled with restricted cubic splines (specifically, rms::rcs
), posterior_epred
fails when giving newdata
in which one of the spline covariates has a range of values (over which to evaluate the conditional effect) and the other is fixed at one value.
The problem seems to be that posterior_epred
tries to create splines based on the newdata
input, but this is of course not meaningful with a single-valued covariate.
Reprex:
Prep work:
library(rstanarm)
library(dplyr)
dat <- arrange(infert, stratum) %>%
filter(parity <= 2) %>%
mutate(test_covar = rnorm(n(), 10, 3))
nd <- data.frame(age = 18:45, spontaneous = 0, induced = 0, stratum = "1",
case = c(1, rep(0, 27)), test_covar = 8)
Works:
post <- stan_clogit(case ~ rms::rcs(age) + test_covar + spontaneous + induced,
strata = stratum, data = dat, QR = TRUE)
mu <- posterior_epred(post, newdata = nd)
rowSums(mu) # all 1
Fails (the model trains):
post2 <- stan_clogit(case ~ rms::rcs(age) + rms::rcs(test_covar) + spontaneous + induced,
strata = stratum, data = dat, QR = TRUE)
mu2 <- posterior_epred(post2, newdata = nd)
with this message:
fewer than 3 unique knots. Frequency table of variable:
x
8
28
Error in rcspline.eval(x, nk = nknots, inclx = TRUE, pc = pc, fractied = fractied) :
In addition: Warning message:
In rcspline.eval(x, nk = nknots, inclx = TRUE, pc = pc, fractied = fractied) :
5 knots requested with 1 unique values of x. knots set to -1 interior values.
Versions and OS:
I run rstanarm v2.21.1 in Rstudio with R v3.6.3 on MacOS X 10.15 Catalina.