--- title: "Getting started with flexCountReg" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Getting started with flexCountReg} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 4) ``` This tutorial walks through a complete first analysis: describing count data, fitting a Poisson regression, checking whether its variance assumption holds, comparing alternatives fitted to the same rows, and turning the chosen model into predictions with uncertainty. ## The question and the data `InsectSprays` (in base R's datasets package) records the number of insects counted in agricultural experimental units treated with one of six insecticides, labelled A to F (Beall, 1942). The questions are: * How does the expected insect count differ between sprays? * How much do counts vary between units treated with the same spray? ```{r setup} library(flexCountReg) d <- datasets::InsectSprays str(d) ``` The observational unit is one experimental unit. The outcome `count` is a non-negative whole number; `spray` is a factor with six levels. There is no exposure variable (all units are treated as comparable), no grouping beyond the spray, and no missing values: ```{r inspect} anyNA(d) table(d$spray) range(d$count) ``` ## Describe the counts ```{r describe-plot, fig.cap = "Insect counts by spray (each point is one unit; the bar marks the mean)."} set.seed(1) # the horizontal jitter is random stripchart(count ~ spray, data = d, vertical = TRUE, method = "jitter", pch = 1, xlab = "Spray", ylab = "Insect count") means <- tapply(d$count, d$spray, mean) segments(seq_along(means) - 0.25, means, seq_along(means) + 0.25, means, lwd = 3) ``` ```{r describe-table} grp <- data.frame(mean = tapply(d$count, d$spray, mean), variance = tapply(d$count, d$spray, var)) grp$ratio <- grp$variance / grp$mean round(grp, 2) ``` Over all units the variance-to-mean ratio is `r round(var(d$count) / mean(d$count), 1)`, far above the value of 1 implied by a Poisson distribution. That number is only descriptive: most of it comes from the large differences in means between sprays, which a regression on `spray` explains. Within sprays the ratios are much closer to 1 (between `r round(min(grp$ratio), 2)` and `r round(max(grp$ratio), 2)`). Whether that is real overdispersion is a question for the fitted models below. ## A Poisson regression ```{r poisson} pois <- countreg(count ~ spray, data = d, family = "POISSON", method = "BFGS") summary(pois) ``` The Poisson model has a log link, so `exp(coefficient)` is a rate ratio: the expected count for a spray relative to spray A (the reference level). ```{r poisson-tidy} tidy(pois, conf.int = TRUE, exponentiate = TRUE) ``` For the Poisson family, `countreg()` maximizes the same likelihood as `glm()`, and the results agree: ```{r glm-check} ref <- glm(count ~ spray, data = d, family = poisson()) all.equal(unname(coef(pois)), unname(coef(ref)), tolerance = 1e-6) all.equal(as.numeric(predict(pois)), as.numeric(fitted(ref)), tolerance = 1e-6) ``` ## Is the Poisson variance adequate? With only a factor in the model, each spray's expected count is its sample mean. What remains to check is the variance. The Pearson statistic divided by its residual degrees of freedom should be close to 1 for a Poisson model: ```{r pearson} pearson <- function(fit, k) sum(residuals(fit, type = "pearson")^2) / (nobs(fit) - k) pearson(pois, length(coef(pois))) ``` A rootogram compares the observed frequency of each count with the frequency expected under the fitted model (hanging bars that end above or below zero mark counts that are under- or over-predicted): ```{r rootogram-pois, fig.cap = "Hanging rootogram of the Poisson model."} rootogram(pois, main = "Poisson") ``` Randomized quantile residuals are approximately standard normal when the model is correct. They involve random numbers (counts are discrete), so set a seed to make them reproducible: ```{r qres-pois, fig.cap = "Randomized quantile residuals of the Poisson model against the fitted means."} set.seed(2026) qr_pois <- residuals(pois, type = "quantile") plot(predict(pois), qr_pois, xlab = "Fitted mean", ylab = "Quantile residual", main = "Poisson") abline(h = c(-2, 0, 2), lty = c(2, 1, 2)) ``` A Pearson ratio of `r round(pearson(pois, 6), 2)` suggests some extra variation within sprays beyond the Poisson variance. ## Alternatives fitted to the same rows Two common extensions of the Poisson model add a dispersion parameter $\alpha$: * NB2: $Var(Y) = \mu + \alpha\mu^2$ (extra variance grows with the square of the mean); * NB1: $Var(Y) = \mu(1 + \alpha)$ (extra variance proportional to the mean). Both keep the same mean model, so their coefficients have the same rate-ratio interpretation. ```{r alternatives} nb2 <- countreg(count ~ spray, data = d, family = "NB2", method = "BFGS") nb1 <- countreg(count ~ spray, data = d, family = "NB1", method = "BFGS") c(poisson = nobs(pois), nb2 = nobs(nb2), nb1 = nobs(nb1)) ``` All three models use the same `r nobs(pois)` rows, so their likelihoods are comparable. Each summary reports a likelihood-ratio test against the Poisson model; because a dispersion of zero is on the boundary of the parameter space, the p-value uses a 50:50 mixture of chi-square distributions: ```{r nb2-summary} summary(nb2) ``` ```{r compare} cmp <- data.frame( model = c("Poisson", "NB2", "NB1"), logLik = c(logLik(pois), logLik(nb2), logLik(nb1)), parameters = c(length(coef(pois)), length(coef(nb2)), length(coef(nb1))), AIC = c(AIC(pois), AIC(nb2), AIC(nb1)), BIC = c(BIC(pois), BIC(nb2), BIC(nb1)), LR_p_vs_Poisson = c(NA, summary(nb2)$lr_test$p.value, summary(nb1)$lr_test$p.value)) cmp[, -1] <- round(cmp[, -1], 3) cmp ``` Both negative binomial models improve on the Poisson model (likelihood-ratio p = `r round(summary(nb2)$lr_test$p.value, 3)` for NB2 and `r round(summary(nb1)$lr_test$p.value, 3)` for NB1), and AIC prefers either of them; BIC, which penalizes the extra parameter more, is about the same for all three. The evidence for extra variation is modest but consistent. ### A limitation to recognize: two models that the data cannot separate NB1 and NB2 differ only in how the extra variance grows with the mean, and their log-likelihoods differ by `r round(abs(as.numeric(logLik(nb2) - logLik(nb1))), 2)`. Neither model is a special case of the other, so a likelihood-ratio test between them is not valid, and flexCountReg does not report one: ```{r not-nested} regCompTest(nb1, model2 = nb2)$statistics ``` With only 12 units per spray, the data cannot tell the two variance forms apart. What matters for the question is that the spray effects are almost the same under all three models: ```{r effects} round(cbind(Poisson = coef(pois)[1:6], NB2 = coef(nb2)[1:6], NB1 = coef(nb1)[1:6]), 3) ``` The rest of the tutorial uses NB2, the more common choice; using NB1 instead would not change the conclusions. ```{r rootogram-nb2, fig.cap = "Hanging rootogram of the NB2 model."} rootogram(nb2, main = "NB2") ``` ## Predictions by spray A prediction grid with one row per spray makes the comparison explicit. A confidence interval describes the uncertainty about the expected count; a prediction interval describes where a single new unit's count is likely to fall, so it is much wider: ```{r predict} new_spray <- data.frame(spray = factor(levels(d$spray), levels = levels(d$spray))) ci <- predict(nb2, newdata = new_spray, interval = "confidence") pr <- predict(nb2, newdata = new_spray, interval = "prediction", level = 0.90) pred <- data.frame(spray = new_spray$spray, expected = ci$fit, ci_lower = ci$lwr, ci_upper = ci$upr, pi90_lower = pr$lwr, pi90_upper = pr$upr) pred[, 2:4] <- round(pred[, 2:4], 2) pred # Sprays below the overall mean, and whether their confidence intervals # are separated from those of the other sprays low <- ci$fit < mean(d$count) separated <- max(ci$upr[low]) < min(ci$lwr[!low]) ``` ```{r predict-plot, fig.cap = "Expected counts with 95% confidence intervals (thick) and 90% prediction intervals for a new unit (thin)."} x <- seq_len(nrow(pred)) plot(x, pred$expected, ylim = range(0, pr$upr), xaxt = "n", pch = 19, xlab = "Spray", ylab = "Insect count") axis(1, at = x, labels = pred$spray) segments(x, pr$lwr, x, pr$upr, lwd = 1) segments(x, ci$lwr, x, ci$upr, lwd = 4) ``` The intervals are computed from the fitted model's estimation uncertainty using deterministic Halton draws, so rerunning gives the same values; the prediction-interval limits are whole counts. See `?predict.flexCountReg` for the method, and `?tolerance_interval` for intervals intended to contain a stated share of all units' counts. These are model-based comparisons of the sprays in this experiment. Sprays `r paste(pred$spray[low], collapse = ", ")` have expected counts below the overall mean, and their 95% confidence intervals `r if (separated) "are entirely below" else "overlap"` those of sprays `r paste(pred$spray[!low], collapse = ", ")`. Interpreting the differences as effects of the insecticides relies on the design of the original experiment, not on the model. ### Another pitfall: levels not seen in the data Predictions use the factor levels of the training data. A level that was never observed has no coefficient, and `predict()` stops with an informative error rather than guessing: ```{r new-level} tryCatch(predict(nb2, newdata = data.frame(spray = "G")), error = function(e) conditionMessage(e)) ``` ## The analysis in one script ```{r script, eval = FALSE} library(flexCountReg) d <- datasets::InsectSprays pois <- countreg(count ~ spray, data = d, family = "POISSON", method = "BFGS") nb2 <- countreg(count ~ spray, data = d, family = "NB2", method = "BFGS") summary(nb2) rootogram(nb2) new_spray <- data.frame(spray = factor(levels(d$spray), levels = levels(d$spray))) predict(nb2, newdata = new_spray, interval = "confidence") predict(nb2, newdata = new_spray, interval = "prediction", level = 0.90) ``` ## Next steps * `vignette("choosing-a-count-distribution", package = "flexCountReg")` compares many more distributions and models for the dispersion and the zeros. * `vignette("inference-prediction-and-comparison", package = "flexCountReg")` covers standard errors, marginal effects and the conditions under which likelihood-ratio tests are valid. * `?count_families` lists every distribution available in `countreg()`. * `vignette("predictions-and-effects", package = "flexCountReg")` interprets predictions, contrasts and marginal effects. * `vignette("data-exposure-weights", package = "flexCountReg")` covers offsets, weights and the analysis sample. * `vignette("diagnosing-count-models", package = "flexCountReg")` checks a fitted model with residuals and rootograms. ## Reference Beall, G. (1942). The transformation of data from entomological field experiments so that the analysis of variance becomes applicable. *Biometrika*, 32(3/4), 243-262.