Skip to contents

glmm_fit() fits a GLM with random effects, log(mu) = X beta + offset + sum(z' b), each grouping factor's effects at a level N(0, Sigma) with Sigma unstructured (a standard deviation for each term and their correlations), for the Poisson, gamma or Tweedie (fixed power in (1, 2)) with the log link, by maximum marginal likelihood as glmmTMB and lme4::glmer(): the Laplace approximation by default, or adaptive Gauss-Hermite quadrature with nodes nodes for a single factor with a single term (glmer(nAGQ = nodes)). The dispersion is estimated by maximum likelihood, as glmmTMB does. Random terms are written as in lme4: (1 | g), crossed factors (1 | a) + (1 | b), nested ones (1 | a/b) (that is, (1 | a) + (1 | a:b)), a random slope on a numeric covariate correlated with the intercept (1 + x | g) (or (x | g)), without the intercept (0 + x | g), and independent of it (1 + x || g). The results match glmmTMB and glmer (validation/scripts/r_glmm.R; docs/design/models.md, "Mixed models").

Usage

glmm_fit(
  formula,
  data,
  family = "poisson",
  power = NULL,
  nodes = NULL,
  offset = NULL,
  weights = NULL
)

glmm_model(ptr, terms, xlevels, groups)

Arguments

formula

A formula with the fixed effects and one or more random terms, (1 | g) or (1 + x | g).

data

A data frame.

family

"poisson", "gamma" or "tweedie".

power

The Tweedie power, in (1, 2).

nodes

Quadrature nodes for a single grouping factor; NULL for the Laplace approximation.

offset, weights

Optional offset (added to any offset() term) and prior weights.

Value

A glmm_model with coefficients, std_errors, covariance (of the coefficients), sd and sd_std_errors (each random term's standard deviation, named g for a factor's intercept and g|x for its slope on x; the error is NaN for one at 0), correlations (each factor's correlation matrix of its terms), dispersion and dispersion_std_error (phi: the variance is phi mu^p / w; 1 for the Poisson), log_likelihood, aic, bic, fitted, iterations, converged, and random_effects: a list by factor of data frames with a row for each level and term, its conditional mode value, its conditional_variance (lme4's condVar) and its prediction_variance (with the estimates' uncertainty, glmmTMB's condVar). predict() adds each row's effects by label and covariate; a level the fit has not seen, or a factor whose columns (its labels' or its slopes') newdata lacks, adds 0, the population mean.

Examples

d <- data.frame(y = (0:39 * 7) %% 5 + 0:39 %% 4, site = paste0("s", 0:39 %% 4))
m <- glmm_fit(y ~ 1 + (1 | site), d)
m@sd
#>      site 
#> 0.2835027 
predict(m, data.frame(site = c("s0", "new")))
#> [1] 2.413623 3.365491