Skip to main content
v2026.11,986 entries · CC-BY 4.0

How to Fit and Evaluate a Poisson Model in R

Learn how to fit a Poisson model in R using glm(), handle offsets for rates, interpret incidence rate ratios, and test for overdispersion with diagnostics.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

A Poisson model in R is fitted using the base stats function glm(formula, family = poisson(link = 'log'), data = dataset), which estimates maximum likelihood parameters for non-negative count dependent variables through iteratively reweighted least squares. Researchers use this generalized linear model to analyze discrete event frequencies, model incidence rates across unequal exposure periods using an offset term such as offset(log(exposure)), and calculate exponentiated coefficients that represent incidence rate ratios.

Ask CASRAI · free to tryQuestion about this guide? Ask CASRAI answers with linked sources. 2 free questions a day, no account.

Ask your first question freeSubscribe

What it is used for in research

Count data arise across diverse quantitative research disciplines, including epidemiology, health economics, bibliometrics, ecology, political science, and operations research. Unlike continuous variables that follow Gaussian distributions, count outcomes represent non-negative integers (0, 1, 2, …, y) characterized by heteroskedasticity, positive skewness, and discrete probability mass at zero. Applying ordinary least squares (OLS) linear regression to count outcomes violates homoskedasticity and normality assumptions, frequently generating nonsensical negative predicted values. A Poisson model overcomes these limitations by modeling the expected count through a logarithmic link function, ensuring all fitted values remain strictly positive.

In biomedical and clinical studies, Poisson models evaluate adverse drug events, patient readmission frequencies, and infection occurrences over variable hospital lengths of stay. In bibliometric and meta-research workflows, researchers quantify journal citation frequencies, patent filings, or researcher grant application counts. When observations differ in observation windows, geographic land area, or population size, researchers incorporate an exposure offset to transform raw count modeling into incidence rate modeling. As documented in the core glm function in R, the Poisson family serves as the canonical generalized linear model for independent discrete event counts where the occurrence of one event does not alter the probability of subsequent events.

How to install or access it

The foundational function for fitting a Poisson model in R is glm(), which belongs to the base stats package. Because stats is bundled directly with the R distribution maintained by the R Foundation for Statistical Computing, no external package installation is required to fit standard Poisson regression models or evaluate deviance statistics. R can be obtained directly from the Comprehensive R Archive Network (CRAN) at cran.r-project.org for Linux, macOS, and Windows operating systems.

To verify that R is installed and check your active R version, execute the following command in your terminal or R console:

# Check active R version and platform details
R.version.string
# Verify stats package availability
packageVersion('stats')

While base R fits Poisson and Quasi-Poisson regressions, comprehensive research diagnostics often require companion packages hosted on CRAN. Specifically, Cameron and Trivedi’s formal dispersion test is implemented in the AER package, negative binomial modeling is provided by the MASS R package, robust standard error calculation relies on the sandwich package, and zero-inflated modeling is available via pscl or glmmTMB in R. Install these verified CRAN packages using standard repository commands:

# Install official CRAN diagnostic packages
install.packages(c('AER', 'MASS', 'sandwich', 'lmtest', 'pscl'))

Step-by-step task

Fitting and interpreting a Poisson regression model in R follows a five-step quantitative workflow. The step-by-step instructions below demonstrate data preparation, model estimation with an exposure offset, calculation of incidence rate ratios (IRR), and empirical assessment of model assumptions.

Step 1: Prepare and inspect count data

Ensure the response variable consists exclusively of non-negative integers (0, 1, 2, …). Check for missing observations and verify the distribution of the outcome. In the reproducible example below, we simulate an epidemiological cohort study examining patient clinic visits based on age group, chronic condition status, and person-months of follow-up exposure:

# Set seed for reproducibility
set.seed(42)
n <- 500
age <- rnorm(n, mean = 50, sd = 10)
chronic <- rbinom(n, size = 1, prob = 0.35)
person_months <- round(runif(n, min = 6, max = 36))

# Generate true Poisson rate with log link: lambda = exposure * exp(eta)
eta <- -3.5 + 0.02 * age + 0.65 * chronic
mu <- person_months * exp(eta)
visits <- rpois(n, lambda = mu)

# Construct research data frame
clinic_data <- data.frame(visits, age, chronic, person_months)
head(clinic_data)

Step 2: Fit the Poisson model with an exposure offset

When observational units possess unequal follow-up intervals, population sizes, or sampling efforts, modeling raw counts confounds event frequency with exposure volume. Mathematically, the expected rate satisfies log(μ / t) = β0 + β1x1 + … + βkxk. Rearranging this equation yields log(μ) = log(t) + Xβ, where log(t) enters the linear predictor with its regression coefficient constrained strictly to 1. In R, specify the exposure offset using offset(log(person_months)) directly within the model formula or via the dedicated offset argument:

# Fit Poisson Generalized Linear Model with log link and offset
poisson_fit <- glm(
  formula = visits ~ age + chronic + offset(log(person_months)),
  family = poisson(link = 'log'),
  data = clinic_data
)

# Inspect standard model summary
summary(poisson_fit)

Step 3: Extract and exponentiate coefficients (Incidence Rate Ratios)

Raw Poisson regression coefficients represent the expected change in the natural logarithm of the mean count for a one-unit increase in the predictor variable. To provide clear scientific interpretation, exponentiate the estimated coefficients: exp(βj) yields the Incidence Rate Ratio (IRR). An IRR of 1.0 indicates no association, an IRR greater than 1.0 indicates a multiplicative increase in the expected rate, and an IRR less than 1.0 reflects a relative rate reduction. Compute point estimates alongside 95% profile likelihood confidence intervals using the following commands:

# Extract coefficients and 95% profile likelihood confidence intervals
beta <- coef(poisson_fit)
ci_beta <- confint(poisson_fit)

# Exponentiate to obtain Incidence Rate Ratios (IRR)
irr_table <- exp(cbind(IRR = beta, `2.5%` = ci_beta[, 1], `97.5%` = ci_beta[, 2]))
round(irr_table, 4)

Step 4: Conduct formal overdispersion testing

The Poisson distribution enforces the strict equi-dispersion property: the conditional variance of the response must equal its conditional mean (Var(Y|X) = μ). In practical research datasets, unobserved heterogeneity, clustering, or contagion frequently causes overdispersion, wherein observed variance substantially exceeds the mean. Under overdispersion, standard Poisson maximum likelihood coefficient estimates remain statistically consistent, but standard errors are artificially deflated, producing falsely narrow confidence intervals and inflated Type I error rates.

Evaluate dispersion using both a heuristic ratio check and Cameron and Trivedi’s formal score test via the AER package:

# Heuristic dispersion check: residual deviance divided by residual degrees of freedom
dispersion_ratio <- poisson_fit$deviance / poisson_fit$df.residual
cat('Deviance Dispersion Ratio:', round(dispersion_ratio, 3), 'n')

# Formal Cameron and Trivedi (1990) test using AER package
library(AER)
# Test linear alternative (quasi-Poisson form): Var(Y) = (1 + alpha) * mu
disp_test_linear <- dispersiontest(poisson_fit, trafo = NULL, alternative = 'greater')
print(disp_test_linear)

# Test quadratic alternative (negative binomial NB2 form): Var(Y) = mu + alpha * mu^2
disp_test_quad <- dispersiontest(poisson_fit, trafo = 2, alternative = 'greater')
print(disp_test_quad)

Step 5: Compute robust standard errors and generate predictions

If moderate overdispersion is detected, researchers can adjust inference without changing the Poisson point estimates by computing heteroskedasticity-consistent sandwich standard errors. Alternatively, use the fitted model to generate predicted counts or rates on new data using the techniques detailed in our guide to prediction in R:

# Compute robust sandwich standard errors using sandwich and lmtest
library(sandwich)
library(lmtest)
robust_se <- coeftest(poisson_fit, vcov = vcovHC(poisson_fit, type = 'HC0'))
print(robust_se)

# Predict expected visits for new patients over a standardized 12-month period
new_patients <- data.frame(
  age = c(30, 50, 70),
  chronic = c(0, 1, 1),
  person_months = c(12, 12, 12)
)
pred_visits <- predict(poisson_fit, newdata = new_patients, type = 'response')
data.frame(new_patients, Predicted_Visits = round(pred_visits, 2))

Output and how to read it

Calling summary(poisson_fit) produces an extensive diagnostic report divided into six core sections. Understanding each component is essential for reporting research outcomes in compliance with academic standards.

1. Call: Displays the exact model formula, distribution family, and data frame specified in the function invocation. Verify that the link function states family = poisson(link = 'log') and that any necessary offset terms appear correctly.

2. Deviance Residuals: Reports the distribution (Minimum, First Quartile, Median, Third Quartile, Maximum) of the deviance residuals. Deviance residuals measure each observation’s individual contribution to the total model deviance. In a well-specified Poisson model with moderate to large sample size, deviance residuals should be approximately symmetric around zero, with the median near zero and roughly equal absolute values for the first and third quartiles. Extreme skewness or outliers beyond ±3 standard deviations indicate potential unmodeled outliers or extreme zero inflation.

3. Coefficients Table: Contains four standardized columns for each model parameter:

  • Estimate: The estimated regression coefficient (β) on the logarithmic scale. For continuous predictors like age, each one-year increase multiplies the expected event rate by exp(β). For binary indicators like chronic, exp(β) represents the relative rate comparison between positive and reference groups.
  • Std. Error: The asymptotic standard error of the coefficient estimate, derived from the inverse Fisher information matrix.
  • z value: The Wald test statistic, calculated as z = Estimate / Std. Error. Under the null hypothesis that β = 0, this statistic follows a standard normal distribution asymptotically.
  • Pr(>|z|): The two-sided p-value associated with the Wald z-statistic. Values below 0.05 denote statistical significance at the conventional 5% alpha threshold.

4. Dispersion Parameter: In a standard Poisson GLM, R explicitly prints: (Dispersion parameter for poisson family taken to be 1). This confirms that R assumed strict equi-dispersion during parameter optimization. If you instead fit a Quasi-Poisson model, this line displays the estimated dispersion parameter (φ), which scales standard errors by √φ.

5. Null and Residual Deviance: Deviance quantifies unexplained variation by comparing the fitted model against a saturated model:

  • Null deviance: Measures the discrepancy of an intercept-only model (incorporating any offset). Degrees of freedom equal n − 1.
  • Residual deviance: Measures the discrepancy of the fitted model including all explanatory predictors. Degrees of freedom equal n − p, where p is the total number of estimated parameters including the intercept.
  • A substantial reduction from null to residual deviance indicates strong predictive explanatory power. Formally, the difference (Null Deviance − Residual Deviance) follows a chi-squared distribution with degrees of freedom equal to the number of added predictors.

6. AIC and Fisher Scoring Iterations: Akaike’s Information Criterion (AIC = −2log(L) + 2k) penalizes log-likelihood by the number of estimated parameters (k). As analyzed in our comparative review of AIC vs. BIC for model selection, lower AIC values signify superior trade-offs between goodness-of-fit and model complexity. Finally, Number of Fisher Scoring iterations records the convergence cycles of the IWLS algorithm; typical count models converge smoothly within 4 to 8 iterations.

Troubleshooting

When fitting Poisson models to empirical datasets, researchers frequently encounter modeling irregularities. The diagnostics and corrective solutions below address the most prevalent practical challenges.

1. Overdispersion detected (Deviance / df > 1.5 or p < 0.05 in AER test)

When observed count variance exceeds the conditional mean, standard Poisson standard errors are downward-biased. Researchers have two primary solutions. The first is Quasi-Poisson regression, which inflates standard errors proportionally without changing point estimates. The second is Negative Binomial regression, which models overdispersion explicitly by adding a gamma-distributed random effect to the Poisson mean. As detailed in our comparison of Quasi-Poisson vs. Negative Binomial regression, Negative Binomial regression is generally preferred when conducting model selection via AIC or when overdispersion increases quadratically with the mean:

# Remedy A: Quasi-Poisson model (fixes standard error bias, no AIC)
qp_fit <- glm(visits ~ age + chronic + offset(log(person_months)),
              family = quasipoisson(link = 'log'), data = clinic_data)

# Remedy B: Negative Binomial model via MASS (full likelihood, valid AIC)
library(MASS)
nb_fit <- glm.nb(visits ~ age + chronic + offset(log(person_months)), data = clinic_data)
summary(nb_fit)

2. Excess zeroes beyond model expectations

If your dataset contains a higher proportion of zero counts than predicted by the Poisson or Negative Binomial distributions, a single-process model may yield biased predictions. Excess zeroes often reflect two distinct generating mechanisms: structural zeroes (subjects who are incapable of experiencing the event) and sampling zeroes (subjects who are at risk but happened to experience zero events). In these scenarios, fit a Zero-Inflated Poisson (ZIP) or Zero-Inflated Negative Binomial (ZINB) model using pscl::zeroinfl() or glmmTMB, combining a logistic regression component for the zero probability and a count model component:

# Fit Zero-Inflated Poisson model using pscl
library(pscl)
zip_fit <- zeroinfl(visits ~ age + chronic | chronic, data = clinic_data, dist = 'poisson')
summary(zip_fit)

3. Non-integer counts or negative values in response

Executing glm() with family = poisson on non-integer numeric data triggers the standard warning: In dpois(y, mu, log = TRUE) : non-integer x = .... If your dependent variable represents rounded rates, percentages, or continuous density metrics, a Poisson GLM is mathematically inappropriate. If your data represent rates calculated as counts divided by time, convert the rate back to raw integer counts and specify the time denominator inside offset(log(time)).

4. Complete separation or zero cell counts

When a categorical predictor perfectly predicts zero counts (for example, a subgroup where zero events occurred across all subjects), maximum likelihood estimation experiences complete separation. The algorithm fails to converge, resulting in enormous coefficient estimates (β → −∞) and astronomically large standard errors. To resolve separation, collapse sparse factor levels, apply Firth’s penalized maximum likelihood via the brglm2 package, or employ Bayesian count regression using brms or rstanarm with weakly informative priors.

5. Algorithm divergence or step-halving failure

If R prints algorithm did not converge or step size truncated due to divergence, the iteratively reweighted least squares procedure struggled with extreme starting values or severe collinearity among predictors. Standard corrective actions include: (a) standardizing or centering continuous explanatory variables, (b) increasing the maximum number of iterations via control = glm.control(maxit = 100), and (c) providing explicit starting values via the start argument.

Free alternatives

While base R provides a powerful environment for count data regression, quantitative researchers frequently operate across multiple computational platforms. The table below compares free, open-source software alternatives for fitting Poisson regression models, summarizing syntax, offset specifications, diagnostic capabilities, and licensing terms.

Platform / Library Fitting Function Offset Syntax Overdispersion Support License and Availability
R (stats) glm(..., family = poisson) + offset(log(t)) Quasi-Poisson in base; NB2 in MASS; AER test GPL-2 / GPL-3, Open Source
Python (statsmodels) smf.glm(..., family=sm.families.Poisson()) offset=np.log(t) NegativeBinomial class; robust covariance BSD 3-Clause, Open Source
Julia (GLM.jl) glm(..., Poisson(), LogLink()) offset=log.(t) Quasi-likelihood via custom dispersion MIT License, Open Source
gretl poisson y const x --offset=t --offset=varnam Built-in overdispersion test and negbin GPL-3, Open Source GUI and CLI
Stan / brms (R) brm(y ~ x + offset(log(t)), family = poisson) + offset(log(t)) Full Bayesian NB, zero-inflated, and hurdle GPL-2 / BSD, Open Source MCMC

For an expanded comparison of count modeling capabilities across R packages, the data table below compares distribution families, variance formulas, dispersion parameters, and AIC availability across count regression models.

Frequently asked questions

What is the difference between a Poisson model and a negative binomial model in R?

A Poisson model assumes that the variance of the outcome equals its mean (equi-dispersion). In contrast, a Negative Binomial model (fitted using MASS::glm.nb) includes an additional dispersion parameter (θ) that allows variance to exceed the mean according to the quadratic formula Var(Y) = μ + μ2 / θ. When data are overdispersed, the Negative Binomial model produces realistic standard errors and reliable hypothesis tests, whereas standard Poisson regression underestimates standard errors.

How do you interpret Poisson regression coefficients in R?

Raw Poisson regression coefficients (β) represent the expected change in the natural logarithm of the mean count per one-unit increase in the predictor. By exponentiating the coefficient (exp(coef(model))), researchers obtain the Incidence Rate Ratio (IRR). For example, an IRR of 1.15 indicates that each one-unit increase in the independent variable is associated with a 15% increase in the expected event rate, holding other covariates constant.

Why do you use an offset in Poisson regression?

An offset is used when observational units possess unequal observation periods, geographic sizes, or sample exposures. By adding offset(log(exposure)) to the model formula, R fixes the exposure coefficient to 1.0, transforming the dependent variable from a simple event count into an incidence rate (events per unit of exposure).

Can Poisson regression handle negative numbers or non-integers in R?

No. Poisson regression requires the response variable to consist strictly of non-negative integers (0, 1, 2, …). Negative values are mathematically invalid under Poisson maximum likelihood, and non-integers trigger warnings because the Poisson probability mass function is defined only for discrete integers. Non-integer rates should be multiplied back into integer counts, with exposure duration moved into an offset term.

How do you test for overdispersion in an R Poisson model?

A quick heuristic check is to divide the model’s residual deviance by its residual degrees of freedom; a ratio substantially greater than 1.0 (such as > 1.5) suggests overdispersion. For formal statistical testing, use the dispersiontest() function from the AER package, which tests the null hypothesis of equi-dispersion (α = 0) against an overdispersed alternative (α > 0). A statistically significant result (p < 0.05) indicates that overdispersion must be addressed.

What is the difference between Quasi-Poisson and Negative Binomial regression?

Quasi-Poisson regression scales standard errors by a constant dispersion factor (φ) without altering coefficient point estimates or specifying a full parametric probability distribution. Because it is estimated via quasi-likelihood rather than maximum likelihood, it does not yield an AIC for model selection. Negative Binomial regression assumes a full parametric mixture distribution with a quadratic variance function, allowing likelihood ratio tests and AIC-based comparisons.

Sources

Data: Count Data Regression Models in R: Specification, Variance Functions, and Diagnostics

An original comparative reference compiling statistical characteristics, variance assumptions, AIC compatibility, and package implementations across count data generalized linear models in R, sourced from base R stats, MASS, AER, and pscl documentation.

Count Data Regression Models in R: Specification, Variance Functions, and Diagnostics
Model SpecificationDistribution FamilyVariance FunctionDispersion ParameterFree ParametersAIC AvailableR Package
Standard Poisson GLMPoissonVar(Y) = muFixed (phi = 1)0Yesstats
Quasi-Poisson GLMQuasi-likelihood (Poisson)Var(Y) = phi * muEstimated (phi > 0)1Nostats
Negative Binomial (NB2)Negative BinomialVar(Y) = mu + mu^2 / thetaEstimated (theta > 0)1YesMASS
Zero-Inflated Poisson (ZIP)Mixture (Bernoulli + Poisson)Var(Y) = mu(1 - p)(1 + p*mu)Fixed count dispersion, estimated mixing prob p1Yespscl
Zero-Inflated Negative Binomial (ZINB)Mixture (Bernoulli + Negative Binomial)Var(Y) = (1-p)*mu * (1 + mu/theta + p*mu)Estimated dispersion theta and mixing prob p2Yespscl
Hurdle Poisson ModelTwo-part (Truncated Poisson + Zero Hurdle)Var(Y) = truncated variance conditional on Y > 0Fixed count dispersion with independent zero hurdle1Yespscl

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about How to Fit and Evaluate a Poisson Model in R

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →