I am looking for a way to report the number of groups alongside the number of observations using huxtable::huxreg
to create a table of results of a multilevel model predicted with lmer()
. I can write a custom glance method that overwrites the glance.merMod
method from the broom.mixed
package that works when called from R but does not work when calling huxreg()
.
I believe that the issue is that the huxreg function imports both broom
and broom.mixed
as required namespaces inside the function.
What would be the best way to overcome this issue to use the custom glance method (or an alternative other than simply adding rows to existing huxtables)?
Here's a MWE
library(lme4)
library(tibble)
library(huxtable)
library(broom.mixed)
## Simulate multilevel data
sigma <- 0.5
tau <- 0.1
x <- rnorm(100)
w <- rep(rnorm(10), each=10); i <- factor(rep(1:10, each=10))
y <- x + w + rep(rnorm(10, 0, tau), each = 10) + rnorm(100, 0, sigma)
d <- tibble(y, x, w)
m <- lmer(y ~ x + w + (1|i), data=d)
## Custom glance method
glance.merMod <- function(x, ret=tibble::tibble_row()) {
ret$nobs <- nobs(x)
ret$ngrps <- summary(x)$ngrps
return(ret)
}
glance(m) ## Works, returns nobs and ngrps
huxreg(m, statistics = c("nobs", "ngrps")) ## Doesn't work, ngrps missing
You can fix this using tidy_override()
:
m2 <- tidy_override(m,
glance = list(
ngrps = summary(m)$ngrps
),
extend = TRUE
)
huxreg(m2, statistics = c("nobs", "ngrps"))
─────────────────────────────────────────────────
(1)
─────────────────────────
(Intercept) 0.027
(0.064)
x 0.916
(0.063)
w 0.982
(0.075)
sd__(Intercept) 0.096
(NA)
sd__Observation 0.561
(NA)
─────────────────────────
nobs 100
ngrps 10.000
─────────────────────────────────────────────────
*** p < 0.001; ** p < 0.01; * p < 0.05.
You'll probably also want to call set_number_format
on the ngrps
cell.