diff --git a/NEWS.md b/NEWS.md index 23cf1daa..3dabe7b0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -25,6 +25,8 @@ intercept only models by allowing data frames with 0 columns and multiple rows. * Effective number of parameters are computed for K-fold CV not just LOO CV. (#462) +* `stan_clogit()` now allows outcome variable to be a factor. (#520) + # rstanarm 2.21.1 * Compatible with rstan v2.21.1 diff --git a/R/stan_clogit.R b/R/stan_clogit.R index 63d0f7ed..ecc703c4 100644 --- a/R/stan_clogit.R +++ b/R/stan_clogit.R @@ -125,8 +125,7 @@ stan_clogit <- function(formula, data, subset, na.action = NULL, contrasts = NUL group <- glmod$reTrms group$strata <- glmod$strata <- as.factor(mf[,"(weights)"]) group$decov <- prior_covariance - } - else { + } else { validate_glm_formula(formula) mf[[1L]] <- as.name("model.frame") mf$drop.unused.levels <- TRUE @@ -137,6 +136,9 @@ stan_clogit <- function(formula, data, subset, na.action = NULL, contrasts = NUL Y <- array1D_check(model.response(mf, type = "any")) } contrasts <- attr(X, "contrasts") + if (is.factor(Y)) { + Y <- fac2bin(Y) + } ord <- order(group$strata) if (any(diff(ord) <= 0)) { diff --git a/tests/testthat/test_stan_clogit.R b/tests/testthat/test_stan_clogit.R index 442eca4f..cc0dbf7d 100644 --- a/tests/testthat/test_stan_clogit.R +++ b/tests/testthat/test_stan_clogit.R @@ -42,6 +42,16 @@ test_that("stan_clogit runs for infert example", { expect_stanreg(fit) }) +test_that("stan_clogit works when y is a factor", { + d <- infert[order(infert$stratum), ] + d$case <- factor(d$case, labels = c("A", "B")) + SW(fit_factor <- stan_clogit(case ~ spontaneous + induced, strata = stratum, prior = NULL, + data = infert[order(infert$stratum), ], + QR = TRUE, init_r = 0.5, + chains = CHAINS, iter = ITER, seed = SEED, refresh = 0)) + expect_equal(coef(fit_factor), coef(fit)) +}) + test_that("stan_clogit throws error if data are not sorted", { expect_error(update(fit, data = infert), regexp = "Data must be sorted")