zero_test(): exact Poisson-binomial or parametric
bootstrap test of zero modification (or of any count value) for any
countreg() model. It compares the observed number of zeros
with the number expected under the fitted model and needs no
zero-inflated fit. The exact version handles integer frequency weights
and switches to a normal approximation above exact_max_n
observations; the bootstrap refits the model to each simulated
dataset.bootstrap_lrtest(): parametric bootstrap
likelihood-ratio test for nested countreg() fits, for
comparisons without a valid chi-square reference distribution (such as a
zero-inflation model with covariates). The larger model is refitted from
two starts in each replicate.regCompTest() now reports a boundary-corrected LR test
(50:50 mixture of chi-square(0) and chi-square(1)) when the larger model
adds a constant zero-inflation component, and explains why no test is
reported for zero models with covariates, hurdle models or two boundary
restrictions. The single-model workflow is unchanged.testing-for-excess-zeros: why the Vuong
test is not valid for a model and its zero-inflated counterpart, and how
to use the tests above.predict(type = "prob") takes counts, the
counts to evaluate (such as 0:10, 5:8 or
c(0, 1, 10)), besides max_count (short for
0:max_count). Only those counts are evaluated.
underflow = TRUE adds the probability below the smallest
count, as overflow = TRUE does above the largest.
counts also works for countreg_mv()
("prob" and "conditional") and the finite
mixtures.type = "prob" for countreg_rp(),
countreg_fe(), countreg_hier(),
renb(), repois(), poislind_re()
and negmultinom(): the marginal distribution of a count of
a new unit, with its random terms integrated out
(countreg_fe(): given the estimated group effect;
countreg_hier(): given the estimated effects, or marginal
with marginal = TRUE). rootogram() works for
these models too, and for countreg_mv() draws one rootogram
per outcome (outcome selects some of them).countreg_alloc(): type = "total_prob" and
"count_prob" give the count probabilities of the total and
of each category.interval =) for
every estimator except countreg_fe(), whose group effects
have no covariance matrix. Models with several outcomes return a list of
data frames. In a simulation with 10 models (150 replications, level
0.90), the confidence intervals covered 0.86 to 0.93 of the true means
and the prediction intervals 0.94 to 0.99 of new counts (discrete counts
make them conservative).NA probabilities in
hurdle models (where P(0) was returned) and countreg_mv()
models (where they were 0).margEffTable() works for countreg_alloc()
models: effects on the expected count of each category and on the total,
with standard errors (it averaged over the categories, without standard
errors).fit_resamples_counts(): resamples workflows or
specifications with several outcomes, which
tune::fit_resamples() cannot, and computes the
out-of-sample log score of the count distribution for any engine.count_reg() has every estimator as an engine:
"flexCountReg" (countreg()),
"countreg_rp", "countreg_mix",
"countreg_lc", "countreg_fe",
"countreg_hier", "countreg_alloc",
"countreg_mv", "renb", "repois",
"poislind_re" and "negmultinom". New article
vignette("tidymodels")."conf_int" and
"pred_int" (all engines except "countreg_fe")
and "raw", whose opts reach every option of
predict(). The engine argument predict_args
sets predict() options for numeric predictions and
intervals; fit_engine is the estimators’
engine.count_reg() had no update()
method, so every tune_grid() and
finalize_workflow() failed. New tuning parameters
count_components(), count_zero_type(),
count_correlated() and count_re_dist().rmse() and mae() no longer break yardstick
when flexCountReg is loaded after it: with a data frame they call the
yardstick metric, and they work in metric_set().add_formula()),
columns named in offset, group_var,
panel_id, cluster, fixef,
cre_group or time (and the variables of
rpar_formula with "countreg_rp") no longer
enter the mean model. The documentation wrongly said that columns with a
non-predictor role reach the model; it now describes what works.weight_type is set (the previous warning for importance
weights never appeared, because parsnip passes only their values).update() (which now also has a method for them) and with
bootstrap refits when flexCountReg is not attached. Their stored call
holds the argument values.predict() for countreg_alloc(),
countreg_mv() and countreg_hier() models
accepts new_data; it was ignored, so the predictions were
those of the training data.augment() methods for countreg_alloc() and
countreg_mv().A review of the whole package found the following problems, now fixed, each with a regression test.
countreg_alloc(),
countreg_mv(), correlated random parameters in
countreg_mix() / countreg_lc()): flipping
Cholesky columns after the fit to report positive standard deviations
now flips the stored simulation draws too (for mixtures, each class’s
own draws), so the reported estimates, log-likelihood, scores, Hessian,
robust standard errors and posterior weights all belong to the simulated
optimum. Before, the log-likelihood at the reported estimates could be
lower than the reported maximum (by about 1 to 4 in the review’s
examples).countreg_mv() copulas: probabilities of counts in the
upper tails of their distributions (and other rows whose copula corners
cancel) are now integrated over the upper-tail probabilities instead of
differenced near 1, keeping their relative precision with analytic
gradients. Such rows used to collapse to probability 0 and could distort
the fitted dependence (one extreme pair in independent data gave a Frank
theta of -6.56). Joint and conditional predictions use the same
computation.countreg_alloc() and countreg_mv() with
random parameters: frequency weights now multiply each unit’s
log-likelihood (they entered inside the simulated average, so rescaling
the weights changed the estimates). With group_var, weights
must be constant within units.countreg_alloc() with truncated = TRUE:
predict(type = "total_positive") and
conditional = TRUE with random parameters now average E(c |
b) / (1 - P0(b)) over the random parameters, as the likelihood implies;
simulate() with a shared site-year term redraws the shared
term with each rejected total (it sampled a different distribution and
could leave zero totals).countreg_alloc(), countreg_mv(), the
mixtures’ count probabilities and moments) use Gauss-Hermite grids
(exact for the lognormal means of normal random parameters) instead of
plain Halton points, which reach only about three standard deviations
and biased expected counts by 1-4%. Mixture component means are exact
(from the moment generating function) when the family’s mean is
proportional to mu, and Inf with a warning where the
expected count does not exist (a lognormal random parameter with a
positive covariate, or a gamma random parameter with large variance), as
in countreg_rp(); margEffTable() then stops
with a clear message.newdata.repois() uses its analytic score in the optimizer, the
stored scores and the final Hessian (its standard errors came from
numerical derivatives and were off by up to a factor of three with panel
weights); poislind_re() gains an analytic score, so its
standard errors are accurate.dpoisweibull(),
ppoisweibull(), family = "PW") no longer
returns Inf, NaN or probabilities above 1 for
large or very small Weibull shapes; the quadrature finds the peak of the
integrand with a bracketed search and checks its own accuracy.DPO and GAMMACOUNT: the mean equation is
solved across the documented shape range (the probability was 0 below a
shape of about 0.003-0.005); DPO also needs mu / phi below
about 1e10 (documented).countreg_fe(): groups whose observations, counting
frequency weights, number one are dropped as single observations (the
rule counted rows, so weighted fits differed from the expanded data);
predict(newgroup = "mean_fe") uses a fixed mean of the
estimated effects (weighted by the groups’ sizes) instead of one that
depended on the other rows of newdata.lm(), unused levels are
dropped in every formula, including random-effect terms of
countreg_hier().vcov(type = "robust") works for
countreg_fe() fits (the groups are the units for the
conditional and concentrated likelihoods).cbind(...) ~ . works in countreg_alloc()
and no longer uses the other outcomes as predictors in
countreg_mv() (the . stands for the columns
other than the counts).temporal_effects() and temporal_tests()
work for countreg_mv() fits (with an outcome
column), for tv(basis = "smooth") with any mgcv basis, and
for tv(1, time = ...) in rpar_formula without
a fixed intercept; smooths written with s() are no longer
reported as time-varying effects, and a tv() term inside an
interaction gives a clear message instead of being ignored.margEffTable() works for countreg_mv()
fits (effects on each outcome’s mean) and no longer reports an effect
for the time variable of tv(basis = "smooth").simulate() (for parametric bootstrapping) now works for
countreg_rp(), renb(), repois(),
poislind_re(), negmultinom() and
countreg_fe(), which refused it before; with
countreg(), countreg_hier(), the mixtures,
countreg_alloc() and countreg_mv() every
estimator simulates. Each simulation draws the model’s random terms
anew: each unit’s random coefficients (countreg_rp(), one
draw per panel or row, with correlations and heterogeneity in means and
variances), each panel’s random effect (beta for renb(),
gamma for repois() and negmultinom(), Lindley
for poislind_re()), or the counts given the estimated fixed
effects (countreg_fe()). Simulated means equal the models’
expected counts, panels share their effects, and refits on simulated
data recover the parameters.countreg() uses bootstrap standard errors when
bootstraps is given without stderr, as the
other estimators do.variance
function no longer take minutes for PMFs that do not sum to exactly
1.countreg_alloc() fits a total count jointly with
its allocation across categories, such as crashes by severity: the total
follows any count family (with distribution-parameter formulas), and the
split follows an ordered probit or ordered logit model for ordered
categories (such as severity), with generalized thresholds
(threshold_formula), or a multinomial logit model
(link = "mnl") for unordered categories (such as crash
types), with category-specific coefficients. The default multinomial
likelihood is a proper joint likelihood of the category counts
(likelihood-ratio tests, AIC and BIC are valid); with a Poisson total
the categories are independent Poissons, and with an NB2 total and no
covariates the fit equals negmultinom().
likelihood = "fractional" gives the share-weighted
quasi-likelihood of Shabab et al. (2026, AMAR 51:100440), with sandwich
standard errors and no AIC. Zero totals are part of the model (they
contribute P(c = 0) and nothing about the split);
truncated = TRUE fits a zero-truncated total for data that
hold only units with at least one event, and a message points to it when
the data have no zero totals. predict() gives the expected
counts by category, the probabilities, the total, and the expected total
or counts given at least one event; simulate(),
summary(), tidy(), glance() and
confint() work, and tv() can be used in every
formula. Analytic gradients for all parts.countreg_alloc() has random parameters in each
equation: rpar_total, rpar_alloc (the
propensity) and rpar_threshold (a common random term in the
gaps between thresholds) add normal random deviations to the
coefficients, drawn once per unit of group_var and shared
by its rows (the years of a site), with
correlation = "none", "within" (each equation)
or "across" (between the total and the allocation). The
likelihood is simulated with randomly shifted Halton draws
(rpar_draws, a stored seed) and has analytic
gradients through the draws’ posterior weights. Checked against exact
Gauss-Hermite quadrature (within 0.05 of the log-likelihood with 500
draws) and by recovering correlated random intercepts.
predict() gives marginal predictions and, with
random = "posterior", Empirical Bayes predictions for units
in the estimation data; simulate() draws new coefficients
for each unit; summary() shows the standard deviations and
correlations.countreg_alloc() has a shared site-year term
(shared_formula): one standard normal draw per row that
enters the total, the propensity and/or the threshold gaps
(shared_in) with covariate-dependent loadings, so a row’s
total and its split share an unobserved factor (the term eta of Shabab
et al. 2026, with a loading for each equation, which allows a negative
correlation too). It is integrated by adaptive Gauss-Hermite quadrature
(shared_nodes, centred and scaled for each row; the fit
warns if twice the nodes change the log-likelihood) inside the draws of
the unit-level random parameters, with analytic gradients. With
truncated = TRUE each row’s likelihood is divided by its
marginal probability of a positive total. A Poisson total with the term
only in the total reproduces the Poisson-lognormal (PLN)
fit.countreg_mv() fits several count outcomes observed
on the same units (crashes by severity or type at each site), each with
its own count family, mean formula and distribution-parameter formulas
(family = c(pdo = "NB2", injury = "PIG"), formulas given as
cbind(y1, y2) ~ x or a list of formulas, one per outcome).
In this first version the equations are independent given the
covariates, so the fit equals separate countreg() fits; one
fit gives joint predictions, probabilities, simulations, and Wald tests
across equations. Analytic gradients, a Newton polish after BFGS, and
normal, robust or cluster-robust standard errors. New article on the
website “Multivariate count models”.countreg_mv() has random parameters in each equation
(rpar_formula, one formula for every outcome or one per
outcome), drawn per unit of group_var and correlated across
equations (correlation = "across", the default,
"within" or "none"). Poisson outcomes with
correlated normal random intercepts give the multivariate
Poisson-lognormal model (MVPLN); any family can be used in each
equation. Simulated likelihood with analytic gradients, checked against
numerical derivatives, exact two-dimensional Gauss-Hermite quadrature
and recovery of correlated intercepts. predict() gives
joint (type = "joint") and conditional
(type = "conditional") probabilities of the outcomes, and
Empirical Bayes predictions (random = "posterior");
simulate() draws new random parameters for each unit;
summary() shows the standard deviations and
correlations.countreg_mv() has copulas
(copula = "gaussian" for two outcomes,
"frank", "clayton" or "gumbel"
for any number) that join the outcomes’ own distributions. The
likelihood is the exact probability of the observed counts (the copula’s
volume over the rectangle of each count, summed over the 2^J corners),
not a midpoint or jittered approximation, and all parameters are
estimated together, started from the separate equations (inference
functions for margins). The Gaussian copula uses an exact bivariate
normal distribution function (the algorithm of Genz, accurate to about
1e-15). summary() reports the copula parameter and its
Kendall’s tau, predict() gives joint and conditional
probabilities from the copula, and simulate() draws from
it. Checked against numerical integration, the probabilities’ sums and
margins, independence limits, and recovery of the dependence of every
family.countreg_mv() have analytic gradients
(the derivatives of the copula and of each outcome’s distribution
function), and copulas can be combined with random parameters
(copula with rpar_formula): given a unit’s
random parameters, the outcomes of each row are joined by the copula, so
the random parameters carry the dependence between units over time and
the copula the dependence within each row. Joint and conditional
probabilities and simulations integrate over the random parameters.countreg_alloc() and countreg_mv()
are reported as positive. In countreg_alloc() the intercept
is random only when a random-parameter formula has the term
1 itself (~ 1, ~ 1 + x), as in
the mixtures; ~ x makes only the slope random.countreg_mix() and countreg_lc() have
random parameters within the components (classes), a latent-class
random-parameters model: rpar_formula makes the
coefficients of some variables vary from unit to unit (panel, or row)
around their class means, with class-specific scales
(Component<k>:SD:) or scales shared by all classes
(shared = list(rpar = TRUE)), any of the distributions of
countreg_rp() (rpardists) or correlated normal
parameters (correlated = TRUE), and rpar_draws
simulation draws per unit (the same draws for every class, from a seed
derived from seed). Each class’s simulated likelihood is
that of countreg_rp(), with analytic gradients for the
direct maximization and the EM steps (at most 25 EM iterations per
start, since EM converges slowly here). Predictions, count
probabilities, class probabilities (prior, posterior and history),
residuals, rootogram() and margEffTable()
integrate over the random parameters, and simulate() draws
new coefficients for every unit. Checked against numerical derivatives,
against exact Gauss-Hermite quadrature, and by recovering two classes
with different random slopes.tv(x, time = year) gives
x one effect per period, in the formulas of every
estimator: the mean, the distribution parameters, zero and
underreporting models, countreg_rp()’s
rpar_formula, and the fixed parts of
countreg_hier(), countreg_fe(),
countreg_mix() and the random-effects models.
tv(1, time = year) gives a time-varying intercept. Four
bases: "step" (default; the first period’s effect and the
change at each later period, so a zero coefficient means equal effects
in adjacent periods), "level" (one effect per period),
"hinge" (the cumulative “spline indicators” of Shabab et
al. 2026, AMAR 51:100440, where a zero coefficient continues the earlier
trend instead of keeping the effect equal) and "smooth"
(the varying-coefficient smooth s(time, by = x)). The step,
level and hinge bases give the same fit. The periods are stored for
prediction; a period not in the estimation data is an error, or uses the
nearest period with new_time = "nearest".temporal_effects() gives each period’s effect with
its standard error (A V A’) and confidence interval, and
temporal_tests() gives Wald tests that the effects are
equal in all periods and of each change between adjacent periods. Both
work for every basis, give the same results for the step, level and
hinge bases, and accept a robust vcov.margEffTable() does not treat the time variable of a
tv() term as a predictor.countreg() and countreg_rp() gain
weight_type = c("frequency", "sampling"). Frequency weights
(the default) count each row as that many independent observations, as
before. Sampling (survey or inverse-probability) weights make the
weighted log-likelihood a pseudo-likelihood: standard errors default to
the robust sandwich with meat sum((w s)(w s)’) and a G / (G - 1) factor,
so they do not change when all weights are rescaled (with frequency
weights, multiplying every weight by 100 shrinks them 10-fold); the
number of units is the number of rows or panels; the bootstrap is
refused; summary() notes that LR tests, AIC and BIC are not
valid; and regCompTest() runs no LR test.countreg_rp() now gives the optimizer the analytic
gradient of the simulated log-likelihood instead of a numeric one. Each
panel’s score is the posterior-weighted average over draws of the
family’s score in the log mean times the derivative of the log mean in
each parameter. This covers fixed coefficients; normal, lognormal,
uniform, triangular and gamma random parameters; correlated (Cholesky)
parameters; heterogeneity in means and in variances; and
distribution-parameter formulas. Poisson, NB1, NB2 and NBP have
closed-form scores. The other families use central differences in the
log mean and in each distribution parameter, which take two density
evaluations per distribution parameter whatever the number of regression
parameters. On washington_roads with three random
parameters (9 parameters), a 500-draw NB2 fit by BFGS takes 8.6 s
instead of 41 s, and a 100-draw fit by BHHH takes 6 s instead of 38 s,
with the same log-likelihood. Newton-Raphson’s Hessian is now the
numeric derivative of the analytic gradient, which is faster and more
accurate than second differences of the log-likelihood.
options(flexCountReg.rp_gradient = "numeric") restores the
numeric gradient.countreg_rp() no longer reports convergence where the
optimizer only stopped because the log-likelihood changed little between
iterations. BHHH, NR and BFGSR stop on that test, and a crawling BHHH
also meets it far from the maximum. On washington_roads, a
100-draw NB2 fit with three random parameters started from the matching
countreg() fit “converged” at -1086.9, 21.6 below the
maximum. The fit now checks the Newton decrement g’(-H)^-1 g at the
estimates, which is twice the gain a Newton step predicts. Above 0.1 it
sets converged = FALSE and warns with the predicted gain.
Fits with max.iters = 0 by BFGS, which optim()
reported as converged, are flagged the same way. The decrement is stored
as model$newton_decrement.score function in the internal
registry; the NB1, NB2 and NBP scores are shared by
countreg() and countreg_rp().countreg() and countreg_rp() accept the
penalized smooth terms of the mgcv package (s(),
te(), ti(), t2()) in their
formulas:
countreg(): the mean, the distribution-parameter
formulas, the zero model and the underreporting model.countreg_rp(): the fixed part of the mean,
het_mean_formula, het_var_formula and the
distribution-parameter formulas.sp.summary() reports each smooth by its effective degrees
of freedom, with an approximate test (Wood 2013), instead of its basis
coefficients. logLik() counts the total effective degrees
of freedom, so AIC() compares smooth and parametric
models.mgcv::gam() for Poisson and NB2 (with the dispersion
fixed).smooth_estimates() and plot_smooths()
evaluate and plot each smooth with pointwise and simultaneous confidence
bands. Their values equal mgcv’s term predictions.renb(),
repois(), poislind_re() and
negmultinom() also accept smooth terms, in the mean and,
for negmultinom(), in the panel-level dispersion formulas.
They have the same penalized fitting, sp argument and
Bayesian standard errors. negmultinom() with family NM2 and
repois() are the same model, and give the same smooth.repois() gains an analytic score for its penalized
fits, which made a smooth fit about 10 times faster (46 s to 4 s on
washington_roads).countreg_fe() accepts smooth terms of variables that
change within groups, with all three of its estimators. A smooth of a
variable that is constant within groups is absorbed by the fixed effects
and gives an error.
mgcv::gam() with group dummies: to 1e-8 for one dimension,
1e-14 for two, and 1e-5 for NB2 with the dispersion fixed.countreg_mix() and countreg_lc() accept
smooth terms in the mean, the distribution-parameter formulas and the
mixing (membership) formula.
countreg() exactly.by
smooths (factor by gives a curve per level; numeric
by gives a varying coefficient), random-effect
(bs = "re"), factor-smooth (bs = "fs") and
Markov random field (bs = "mrf", with
xt = list(nb = nb)) smooths. With fixed smoothing
parameters they reproduce mgcv::gam().
smooth_estimates() and plot_smooths() show
every smooth type: curves per level, factor effects with intervals, and
the coefficient of a numeric by.smooth_check(): a basis-dimension check (a k-index with
a permutation p-value) computed from randomized quantile residuals.concurvity_fcr(): the share of each smooth that the
other terms can reproduce, observed and worst case.smooth_derivatives() and
plot_derivatives(): derivatives with pointwise and
simultaneous bands.plot_surface(): two-variable smooths, masked away from
the data.calibration_by(): observed and predicted means,
probabilities of zero and variances by quantile groups of a
covariate.vignette("smooth-effects")).countreg_hier() fits count models with normally
distributed random effects at any number of grouping levels, nested or
crossed, written as in lme4: (1 | site),
(1 + lnaadt | county) (correlated intercepts and slopes),
(lnaadt || county) (uncorrelated),
(1 | county/segment) (nested) and
(1 | site) + (1 | year) (crossed). Every count family can
be used, including user-defined ones, with distribution-parameter
formulas, offsets and frequency weights.engine = "auto" chooses between them. Each covariance
matrix is estimated through its Cholesky factor with an unconstrained
diagonal, so a variance can be estimated as zero; such singular fits are
reported, and the Wald standard errors of that term’s variance
components are not. The derivatives of the log-density are analytic for
the Poisson, NB1 and NB2 families and numerical for the others.lme4::glmer() (Poisson, Laplace and quadrature) and
glmmTMB (Poisson, NB1 and NB2; random intercepts and
slopes, crossed and nested effects), with log-likelihood differences of
1e-6 or less.summary(), predict() with
re.form (condition on all, some or none of the levels),
allow.new.levels and marginal (integrate the
remaining effects out of the mean, exp(eta + z’ Sigma z / 2)),
fitted(), residuals(), simulate()
(with the groups’ effects or new ones), fixef(),
ranef() (conditional modes with posterior variances),
VarCorr(), tidy() and glance().
fixef(), ranef() and VarCorr()
are the nlme generics, so they work alongside lme4.margEffTable() works with countreg_hier()
(the grouping variables are not candidates, and delta-method standard
errors account for the fixed coefficients) and leaves out the regressors
a fixed-effects model removed as not identified.re_lrtest(): likelihood-ratio test of a
random-effect term, with the boundary-corrected (chi-bar-squared)
p-value.s() and t2() in the fixed
part, fitted in their mixed-model form (as in gamm4): the penalized part
of each smooth is a block of normal coefficients with variance 1 /
lambda, so the smoothing parameters are estimated by the marginal
likelihood with the variance components. Smoothing parameters, EDF and
curves equal those of mgcv::gam(method = "ML") with
bs = "re" group effects. A formula with smooths and no
grouping term is a GAM fitted by marginal likelihood.re_dist = "uniform", "triangular" or
"gamma" (one grouping term) gives non-normal random
effects, fitted by maximum simulated likelihood
(engine = "msl", re_draws randomly shifted
Halton draws per group). With "gamma" the multiplicative
group effect is gamma with mean 1; a Poisson model with gamma effects
reproduces repois().predict(history = ) estimates the effects of the groups
from a separate set of past counts, so a forecast never uses its own
outcomes.confint(method = "profile") gives profile-likelihood
intervals for the random-effect standard deviations (and fixed
coefficients); they equal glmmTMB’s.cre and cre_group add the group means of
time-varying covariates (correlated random effects), tested with
cre_test().countreg_hier(): non-normal random
effects at more than one level, smooth terms in the
distribution-parameter formulas, and te()/ti()
smooths (use t2()).countreg_fe() estimates count models with fixed
effects for one or more grouping variables (fixef = ~ site
or ~ site + year). It chooses among three estimators:
fixest::fepois().new_count_family(), with one dimension: the dummy-variable
likelihood with the group intercepts concentrated out.jackknife = TRUE applies the split-panel jackknife of
Dhaene and Jochmans (2015). In simulations with 200 units it removed
most of the NB2 dispersion bias with 5 or 10 periods, but did not
improve the slopes, and it is unreliable below 4 periods, where a
warning is given.predict() uses each known group’s effect. Groups not in
the estimation data give NA unless
newgroup = "mean_fe".fixest::fepois() (one and two ways) and
fixest::fenegbin(). The cluster-robust standard errors
equal fixest’s with ssc(adj = FALSE).countreg_rp(), renb() and
repois() gain cre = ~ x1 + x2 for correlated
random effects (Mundlak 1978). The units’ means of the listed
time-varying regressors are added to the mean model, computed on the
estimation rows and stored with the fit. Predictions for known units use
their training means; new units use the means of their own rows.cre_test(), a Wald test that the coefficients of
those means are zero: a robust test of random against fixed effects. In
simulations with unit effects correlated with the regressor, the plain
random-effects slope was biased (0.63 for a true 0.5), the slope with
cre was 0.505, equal to fixed effects, and the test
rejected in every replication. With uncorrelated effects, it rejected in
7% of replications at the 5% level.countreg() and countreg_rp() gain
stderr = "cluster" with cluster = ~ corridor
(or column names, or a vector of ids). Two or more variables
(~ corridor + year) give multiway clustering (Cameron,
Gelbach and Miller 2011). The scores of the independent units (rows, or
panels) are summed within clusters, with the factor G / (G - 1).
Clusters may be coarser than the panels (sites within corridors) but may
not split a panel. Giving cluster alone selects
cluster-robust standard errors. With frequency weights, a row’s copies
are in its cluster. summary() reports the number of
clusters.vcov() gains
type = c("fit", "hessian", "robust", "cluster") and
cluster, which recompute the covariance matrix from the
stored scores without refitting. This works for countreg(),
countreg_rp(), renb(), repois()
and poislind_re() fits. With
keep_data = FALSE, the clusters are given as a vector.estfun() and bread() methods for the
sandwich package, so sandwich::vcovCL(),
vcovHC(), sandwich(),
lmtest::coeftest() and tools built on them work with
flexCountReg fits. One-way and two-way cluster covariances equal
sandwich::vcovCL(type = "HC0") to 1e-10.new_count_family() and count_param()
define a count distribution from its log PMF, with up to two parameters,
each with a log, logit or identity link. The family object can be passed
as family to countreg(),
countreg_rp(), countreg_mix() and
countreg_lc(). It works with distribution-parameter
formulas, zero-inflated and hurdle models, predictions, quantile
residuals, rootograms, simulate() and robust or
cluster-robust standard errors.
mean, variance, cdf,
rand and valid functions can be given. Without
them, the moments and the CDF come from summing the PMF, and random
draws from inverting the CDF.zero_formula = ~ 1.saveRDS() works in a new R session.check_count_family() checks a family over a grid of
means and parameter values. It tests that the PMF sums to one, that
mean, variance, cdf and
rand agree with the PMF, that the function is vectorized,
and that missing or invalid values cause no errors.launch_app() opens an interactive interface to
flexCountReg in a web browser, with a tab for each step: load a bundled
example or a CSV file and create new variables (logs, powers,
standardized values, indicators, products, ratios, categories, factors);
specify and estimate count regression, random-parameter, random-effects
panel (RENB, Poisson-Lindley, Poisson, negative multinomial),
finite-mixture and latent-class models (any family, exposure or log
offset, frequency weights, distribution-parameter, membership and shared
terms, panels); inspect the summary, coefficients, numerical checks,
class sizes and starts; diagnose fits (rootogram, randomized quantile
residuals, CURE plot); compare them (with the reasons when they are not
comparable); predict for an editable table of scenarios or for uploaded
new data, with confidence, prediction and tolerance intervals for count
regressions; and download the analysis. The Diagnose and Predict tabs
work on any completed model (a selector, which moves to each new fit),
plots can be saved as JPEG files at a chosen size and resolution, and
new data get the variables created on the Data tab that the model needs,
with the means, standard deviations and categories of the training
data.analysis.R; the script reproduces the whole session without
the app (the download also holds the settings of each fit as JSON and a
manifest with versions and warnings). Column names and typed values
enter the code only as names, numbers or strings, never as code. An
action that fails reports its error and leaves the session running.a:b; main effects stay in the
model), and the Fit page has a Marginal effects tab running
margEffTable() (average marginal effects or elasticities;
pseudo-elasticities or discrete changes for indicators; delta-method or
bootstrap standard errors) in the background, with the code added to the
session script and the table downloadable as CSV.data/data_1.csv, data/newdata_1.csv, …)
with its MD5 checksum in the manifest; warnings and messages of every
result are shown beside it and listed in the manifest with the
uncertainty method, accepted bootstrap refits and seed; and stochastic
requests (bootstrap intervals, tolerance intervals, bootstrap marginal
effects) fix their seed when they are made, so the exported script
replays them exactly.countreg_hier(): a grouping column, random slopes,
correlated or uncorrelated, a second level crossed with or nested in the
first, and normal, gamma, uniform or triangular effects) and
fixed-effects models (countreg_fe(): one or two dimensions,
the split-panel jackknife, cluster-robust standard errors by default).
Any model can have smooth (nonlinear) effects s(x) of
numeric predictors, shown on the Diagnose page (“Smooth effects”,
plot_smooths()); random-parameter, hierarchical and
random-effects models can add group means of predictors (correlated
random effects, cre); count regression and random-parameter
models offer cluster-robust standard errors (with a cluster column) and
sampling weights. Predictions for hierarchical and fixed-effects models
take the group of each scenario, and settings files from earlier
versions of the app still load.launch_app() offers to install any that are missing.
app_object() returns the app for deployment or
testing.countreg_mix() estimates finite mixtures of count
distributions and finite-mixture count regressions;
countreg_lc() is the same model under the latent-class
vocabulary (classes, membership_formula). Both
normalize their arguments into one specification and call one engine, so
equivalent calls give identical fits. Supported specifications:
y ~ 1), including fits to
exact-count frequency tables through weights;shared = list(mean = "x")) and shared
distribution-parameter blocks
(shared = list(dis1 = TRUE));mixing_formula = ~ z,
last component as reference), or known fixed proportions
(fixed_mixing), which add no parameters;countreg() in the components, the
same in all of them or different ones
(e.g. family = c(base = "POISSON", tail = "NB2")), with
distribution-parameter formulas;group_var): one class per panel, with
the class probability entering once per panel (product of the rows’
probabilities before the sum over classes);n_starts,
seed), EM iterations with weighted M-steps (analytic scores
for Poisson, NB1 and NB2 components), and direct maximization of the
observed-data log-likelihood to polish the best solutions
(mixture_control(), lc_control()). Every start
is recorded (fit$model$starts), including whether several
starts reached the selected solution. Components of the same family are
numbered by increasing average expected count.stderr = "normal"), unit-level sandwich
scores ("robust"), or a bootstrap of independent units that
refits the full mixture with several starts and aligns component labels
within families ("boot"). The fit records the gradient, the
definiteness and conditioning of the observed information, and ambiguous
bootstrap label matches.summary() (coefficients grouped by component,
shared parameters and mixing model; prior and posterior class sizes;
entropy, relative entropy and ICL; start stability; numerical checks),
print(), coef(), vcov(),
logLik() (free parameters only, independent units for BIC),
predict() with explicit targets
(type = "response", "component",
"variance", "prob", "link";
conditioning = "prior", "history" for panel
forecasts from earlier outcomes only, or the retrospective
"posterior"), fitted(),
residuals() (response, Pearson with the full mixture
variance, and randomized quantile residuals from the mixture
distribution function), simulate() (one class per row or
panel), tidy(), glance() and
augment(). New component_probs() /
class_probs() return prior, history-conditioned or
posterior class probabilities.rootogram() and cureplot() accept mixture
models (prior mixture probabilities and means), and
margEffTable() includes variables that enter only the
membership model (delta-method standard errors with the full covariance
matrix).regCompTest() refuses them, because the chi-square
reference distribution does not hold when the number of components
changes). Zero-inflated, hurdle and underreporting components inside
mixtures and component-specific formulas are not implemented. Mixtures
of families other than Poisson, NB1 and NB2 are labeled experimental:
their component distributions are those of countreg()
(one-component fits agree with it), but recovery of such mixtures has
not been studied.inst/validation/finite-mixtures/ (its
CORES setting runs the replicates in parallel with the same
results). In 200 replicates of each of seven designs (well and weakly
separated Poisson mixtures, a latent-class NB2 regression with
membership covariates and a shared dispersion, a panel latent-class
model, and a Poisson + NB2 mixture), every fit converged; Wald intervals
covered 0.89 to 0.985 (Monte Carlo standard errors about 0.015), and the
label-invariant mixture mean was nearly unbiased in every design. With
weakly separated components and n = 300 the low component’s intercept
was biased (-0.18) and its standard errors unstable, and 40% of the fits
were reached by only one of five starts: use more starts and treat
component-specific inference with caution in such data.summary()) flags components of
the same family with nearly identical parameters: the fit is then
effectively one component fewer and its shares are arbitrary.NA/NaN, NaN with a
warning for invalid parameters, lower.tail,
log/log.p):
ddweib(), pdweib(),
qdweib(), rdweib());ddpo(), …);ddelaporte(),
…);m
(dghermite(), …);dhpois(), …);dgcount(), …);dpaeppli(), …).lower.tail = FALSE) are computed directly rather than as
one minus the distribution function, so tiny tail probabilities keep
their relative accuracy. Quantiles are the smallest count whose
distribution function reaches the requested probability.dnbge(), pnbge(), qnbge(),
rnbge()): NB2 with a mean-one generalized exponential
random effect, computed by the adaptive quadrature used for PGE.countreg() and countreg_rp() gain the
families "DW", "DPO",
"DELAPORTE", "HERMITE" (order 2),
"HERMITE3", "HERMITE4",
"HYPERPOIS", "GAMMACOUNT", "PA"
(Poisson-Tweedie with power 1.5) and "NBGE". All are
parameterized by the mean, so coefficients are effects on the expected
count. For DW, DPO, HYPERPOIS and GAMMACOUNT, whose means have no closed
form, the natural parameter of each observation is found by solving the
mean equation in compiled code; these families are slower to fit and
have a numerical domain (shape in [1e-6, 1e6], mean up to 1e9).rho) use a
logit link, labeled logit(rho).countreg_rp() uses family-specific starting values for
the distribution parameters when the registry provides them (the new
families start at their Poisson or geometric limit rather than at
log-scale -2).predict() gains interval = "confidence"
(for the expected count) and interval = "prediction" (for
one new count), with level, for countreg()
models. Estimation uncertainty is represented by parameter vectors from
the asymptotic normal distribution of the estimates, evaluated at
deterministic Halton points (reproducible), or by a parametric bootstrap
(uncertainty = "bootstrap"), which is also used when the
covariance matrix is not positive definite. Prediction intervals are
integer quantiles of the predictive distribution (the count PMF averaged
over the parameter vectors).tolerance_interval(): content tolerance intervals
(content and confidence levels; two-sided, upper or lower; pointwise or
simultaneous) for countreg() models. The default joint
method returns the narrowest integer interval whose content is at least
the requested fraction at every evaluated point of the confidence set;
the envelope method uses per-tail worst cases; intercept-only Poisson
models use the exact common-rate construction. Zero-inflated, hurdle and
underreporting components are included. A reproducible coverage study is
in inst/validation/intervals/.countreg() now starts the dispersion parameter of NB1,
NB2, PIG1, PIG2 and PIG at a moment estimate from the Poisson starting
fit (the auxiliary regression of Cameron and Trivedi) instead of
alpha = 1. With the old start, quasi-Newton optimizers
could step onto the flat region alpha -> 0 and stop
there with a falsely “converged” Poisson fit: NB2 with
method = "BFGS" gave log-likelihood -228.48 instead of
-195.56 on warpbreaks, and -182.29 instead of -180.11 on
InsectSprays. Results now match
MASS::glm.nb(). Fits that already reached the maximum are
unchanged.NA variances and standard errors
instead of zero (a zero standard error read as perfect precision,
e.g. the random-effect parameter of a Poisson-Lindley random-effects
model at its boundary). The warning names those parameters.NA standard errors; a
warning now names those parameters instead of leaving them silently
NA.inst/validation/simulation-studies/count-regression-study.R
is a parameterized simulation study (Poisson, NB2 and a negative
multinomial panel) with one random-number stream per replicate; its
summary and settings are saved alongside it. The per-replicate results
of this study and of the interval coverage study are kept in the source
repository but left out of the package build.abalone_rings: shell-ring counts and measurements of
4,177 abalone from the UCI Machine Learning Repository (CC BY 4.0), a
non-transportation example with conditionally underdispersed counts. The
preparation script and source hashes are in data-raw/ of
the source repository; data terms are in the installed
DATA-LICENSES.md.stream_salamanders: repeated counts of seven stream
salamander groups at 23 sites (Price et al., 2016; Dryad, CC0), prepared
from the original deposit. Zero-heavy, overdispersed and grouped by
site.tidy(), glance() and
augment() methods, using the generics package (re-exported,
so library(flexCountReg) provides them).
tidy() returns the standard broom columns plus a
component column (mean, distribution, underreporting,
random-parameter and heterogeneity parameters), with
conf.int and exponentiate (incidence rate
ratios for the mean model). tidy() now works for every
estimator. broom is no longer a dependency.count_reg() parsnip model with a
"flexCountReg" and other engines, registered when parsnip
is loaded (parsnip is suggested, not required). The count
family is a main argument and can be tuned with
count_family() (a dials parameter). Case weights are passed
as frequency weights.predict() accepts new_data (the tidymodels
name) as well as newdata.NA (instead of 0) when the
estimated variance is negative, which happens for weakly identified
parameters. regCompTable() shows such standard errors as
NA without significance stars.summary() now returns a
summary.flexCountReg object with a print method
(coefficients with z statistics, the standard-error type,
log-likelihood, AIC, BIC, N and panels, convergence, and a
likelihood-ratio test against Poisson for countreg()
models). Use summary(m)$coefficients for the coefficient
matrix, or tibble::as_tibble(summary(m)) for the tibble
that summary() returned before. The offset is shown as a
note, not as a coefficient row.countreg() and countreg_rp() compute the
final Hessian, and so every Hessian-based, robust and cluster-robust
standard error, adaptively. maxLik’s default step is 1e-6, where
rounding error is about 0.2 per Hessian entry for a log-likelihood near
1000. That made the standard errors of weakly determined parameters
wrong. In the README’s generalized NBP model on
washington_roads they were up to 25% too large (ln(p):
0.229, now 0.183).
countreg_rp() in general) difference the gradient; the
others use second differences of the log-likelihood.model$hessian_accuracy, the largest
relative change of a standard error between the two steps, and warns
when it exceeds 1%.renb() fit by Nelder-Mead on washington_roads
had a negative robust variance for ln(a-1); it is now 0.036. In
well-conditioned fits the change is negligible.countreg_rp() gives each unit (panel, or row without
group_var) its own simulation draws by default: new
argument draws = c("per_unit", "shared"). Unit u uses draws
(u - 1) R + 1 to u R of one Halton sequence, after its first 10 points
(Train 2009, Sec. 9.3.3). With shared draws, as before, draw r is the
same for every panel, so simulation errors are correlated across panels
and do not average out as panels are added. On
washington_roads (NB2, random speed50 and
lnlength, 12 scrambling seeds), per-unit draws cut the
error of the random-parameter means and standard deviations by a factor
of 2 to 5 at 50 and 200 draws. The intercept and the log-likelihood
varied more across seeds than with shared draws. Empirical Bayes
predictions regenerate each estimation panel’s own draws (by panel id),
and new panels get new draws. draws = "shared" reproduces
earlier fits.scrambled = TRUE in
countreg_rp(), and in interval simulations) now depend on
their seed. randtoolbox scrambles with its own generator,
which set.seed() does not reach. So every “scrambled” fit
used the same scrambling (randtoolbox’s default, seed 0), whatever the
stored draw_seed, and different seeds gave identical
results. Fits made before this change still predict with the draws they
were estimated with.countreg_rp(scrambled = TRUE) now randomizes the Halton
draws with a random shift (Cranley-Patterson rotation): each unit’s
block of plain Halton points is shifted by its own uniform amount per
dimension, modulo 1, with the shifts generated from the fit’s
draw_seed. It used randtoolbox’s scrambled (“mixed”) Halton
sequence, whose consecutive per-unit blocks biased the simulated
log-likelihood, and more draws did not remove the bias. For a Poisson
random intercept on washington_roads (exact maximum
-1069.365 by adaptive quadrature), scrambled fits gave -1069.406 at 500
draws and -1069.054 at 2000; with random shifts the error at fixed
parameters averages -0.02 at 500 draws and -0.008 at 2000 (standard
deviation over seeds 0.14 and 0.027). Scrambled fits therefore give
different estimates than before. New fits have draw_version
4; fits with an earlier draw_version still predict with the
“mixed” draws they were estimated with. Prediction intervals with
scrambled = TRUE keep the “mixed” sequence, which uses one
point set and no per-unit blocks.countreg_rp() now uses method = "BFGS" by
default (it was "BHHH"). With the analytic gradient, BFGS
reached the maximum in each of six test models. BHHH failed on two of
the six. On a 500-draw NB2 model with three random parameters it was
still at -1093 after 200 iterations, while BFGS reached -1065.5 in about
10 s. On the same model with 100 draws it reported convergence at the
Poisson boundary (ln(alpha) = -167), 0.08 below the maximum, where no
gradient method can recover. BHHH remains available and is often faster
on simple models. Code that relies on the default can give different
estimates; pass method = "BHHH" to reproduce earlier
fits.maxLik::objectiveFn(fit$model) is unavailable):
its closure held the data, design matrices and draws, so fits were
several times larger than the data (30 MB for 4.3 MB of data).c(<estimator>, "flexCountReg"), with
<estimator> one of countreg,
countreg_rp, renb, poislind_re,
repois and negmultinom. The unused S4 class
definition is removed. The training data are stored once
(obj$data); obj$model$data is gone.regCompTest() with two models now treats the model with
fewer parameters as the restricted model (before: the one with the
higher log-likelihood), errors when the models were fit to different
numbers of observations, and warns when the restricted model has the
higher log-likelihood. Its base and null models use the same rows,
offset and weights as the fitted model. McFadden’s R^2 is computed
against an intercept-only Poisson model for every model by default (so
it is comparable across distributions); a different baseline family,
with or without the mean covariates, can be chosen with
basemodel and variables in both
regCompTest() and regCompTable().cor2cov() stops (instead of warning and returning
NULL) on invalid input, and checks that C is a
symmetric correlation matrix.predict() on probit fits made with earlier versions still
uses the old convention.countreg(): giving an offset both with
offset() in the formula and with the offset
argument is now an error. Before, a formula offset() was
silently ignored.countreg(): an invalid method,
family, stderr or
underreport_family is now an error instead of a warning or
a silent fallback. dis_param_formula_1/_2
given for a parameter the family does not have is an error.countreg() starting values now come from a Poisson GLM
that uses the same rows, offset and weights as the model, so results can
differ slightly (usually closer to the optimum).predict() errors when an offset column used in fitting
is missing from newdata, instead of silently setting the
offset to 0.countreg_rp(): heterogeneity in means now follows Wood
and Gayah (2025, Eq. 2). Each random parameter has its own coefficient
for each variable in het_mean_formula (named
HetMean:<parameter>:<variable>), and the effect
is additive (on the log scale for lognormal parameters; multiplicative
for gamma parameters, whose mean must stay positive). Previously a
single coefficient vector multiplied every random parameter’s mean.
Estimates from models with het_mean_formula change; saved
fits still predict with their original specification.countreg_rp(): uniform random parameters now span mu
+/- St.Dev (draws 2u - 1), matching the paper and the Exact
prediction. Previously the draws spanned mu +/- St.Dev/2, so estimated
uniform St.Dev values are now half as large. predict()
converts saved uniform fits automatically (with a one-time
message).countreg_rp(): rpardists is matched to the
random parameters by name (not position) and validated. An intercept in
both formula and rpar_formula (an unidentified
model) is an error; the intercept implied by rpar_formula
is not a random parameter unless the fixed formula has no intercept. An
invalid panel_id, family or
method is an error.countreg_rp(): weights now weight the
panel log-likelihood (frequency weights for whole panels) instead of
each row’s probability.countreg_rp(): the mixing distribution of PLN, PGE, PLL
and PW families uses its own Halton dimension; it previously reused the
first random parameter’s draws, which made the two perfectly
correlated.predict(method = "Exact") returns Inf
(with a warning) where the expected value does not exist: lognormal
random parameters with a positive x, and gamma random parameters beyond
the domain of their moment generating function. The lognormal formula is
documented as a Laplace approximation.renb() and poisLind.re() require
group_var, and the panels always come from it (a
panel_id column in data is no longer used
instead). Bootstrapped standard errors resample whole panels instead of
rows.pplindLnorm(), qplindLnorm() and
rplindLnorm() convert lambda to
mean consistently with dplindLnorm() (the
extra exp(sigma^2 / 2) factor is removed).dpLnorm(), dpinvgaus(),
dpinvgamma(), dplind() and
dgwar() are vectorized directly instead of through
Vectorize(). Off-support x gives 0 with a
warning, and invalid parameters give NaN with a
warning.dpinvgamma() and the
PIG family) could take minutes, or effectively hang, when the optimizer
tried a small eta. Its log Bessel function took one
recurrence step per unit of order, and the order is about 1/eta. Orders
above 100 now use the uniform asymptotic expansion (accurate to about
1e-10 there), so the cost no longer grows with the order. A bootstrap
refit that took 12 seconds now takes 0.2 seconds.dpinvgaus(), ppinvgaus() and the PIG1/PIG2
families: P(0) was computed as
exp(mu / eta * (1 - sqrt(1 + 2 * eta))), which cancels as
eta -> 0 (at eta = 1e-16 the Type 1 PMF summed to 20, and
ppinvgaus(5, 3, 1e-16) was 18.4), and fits could exploit it
to report a positive log-likelihood. It is now
exp(-2 * mu / (1 + sqrt(1 + 2 * eta))), which tends to the
Poisson value.dsichel() returned -Inf where the log PMF is finite
(for example dsichel(500, 500, 1, 1, log = TRUE)), and
qsichel() (and so rsichel()) stopped at 10,000
for heavy tails. Bessel functions now come from a log-scale order
recurrence, and psichel() and qsichel()
evaluate the PMF in one recurrence sweep and search the support in
doubling blocks.rpinvgaus() cancelled
to 0 for large dispersions; the root is now computed as m / (1 + t +
sqrt(t (t + 2))).dpoisweibull() and friends with mean_value
and sd_value: the shape was searched only in [0.1, 5], so
small coefficients of variation were silently given shape 5 (SD 0.229
instead of 0.01 at mean 1). The shape is now solved from the coefficient
of variation with an expanding bracket.regCompTable(coefs = FALSE) printed the coefficients
anyway, and an unnamed list of models gave a table without model columns
(they are now named “Model 1”, “Model 2”, …).cureplot() no longer prints the cureplots messages
“Covariate: indvar_values” and “CURE data frame was provided…”, which
named the wrapper’s internal objects; other messages are kept. The
documentation of n_resamples now says that the red
reference limits are drawn whatever its value (they were described as
“no bands” at 0).countreg(): offsets given with offset() in
the formula are now used in estimation and prediction.countreg(): bootstrapped standard errors are matched to
parameters by name. They were previously sorted alphabetically and
printed against the wrong coefficients. Failed bootstrap replicates are
counted and reported.countreg(): all data (main formula,
dis_param_formula_1/2, underreport_formula,
offset and weights) are taken from one set of complete cases, so missing
values no longer misalign rows. The number of removed rows is
reported.countreg(): stderr = "robust" and
stderr = "boot" now set the stored standard errors and
covariance matrix ($model$vcov,
$model$vcov_type), which summary() and
margEffTable() use. stderr = "boot" without
bootstraps uses 200 replicates. The SE type is stored in
$model$stderr.countreg(): parameter values where a distribution’s
density fails no longer abort the fit; the likelihood returns
NA so the optimizer steps back.countreg(): start.vals must have one value
per parameter, and named values are matched by name.
$model$converged is now set (with a warning when the
optimizer does not report convergence).predict() returns one value per row of
newdata, in order, with NA for rows with
missing values, instead of recycling shorter vectors. Training factor
levels and contrasts are used, so newdata can contain a
subset of levels. Coefficients are matched by name.predict() sums multiple offset columns and uses formula
offsets.predict() for PLL models now includes the exp(sigma^2 /
2) lognormal mean factor, as it already did for PLN.countreg_rp() now stores its offset, so
predict() uses it. Simulated predictions now include
heterogeneity in means and variances.dpinvgaus() and dpinvgamma() are computed
on the log scale, so they no longer return Inf or
NaN at large counts (e.g. y > 85 with mu = 2, eta =
0.5).rpLnorm(), rplind(),
rplindLnorm(), rplindGamma(),
rpge(), rcom()) accept vector parameters, as
needed for simulation from fitted models. Mixture families draw the
mixing variable per observation.Inf), return NaN for p outside [0, 1], and no
longer recompute the CDF at every step.dplind(lambda = ) uses lambda (it
previously ignored it).poisLind.re() starts from a moment estimate of theta
instead of an undocumented formula.renb() and poisLind.re() use the same data
preparation as countreg(): missing values are removed
consistently, formula offsets work (giving both a formula offset and
offset is an error), and starting values use the
offset.countreg_rp() uses the shared data preparation (formula
offsets, missing values, numeric weights), starts gamma random
parameters from a positive mean, averages panel likelihoods over draws
on the log scale, and reports convergence.predict(method = "Exact") for
countreg_rp() includes heterogeneity in means and
variances.Changed results are marked (changed).
renb() and poisLind.re() accept
weights, as countreg() and
countreg_rp() do. In panel models these are frequency
weights of the panels (constant within a panel): a panel with weight w
counts as w independent panels in the log-likelihood, the robust
covariance, BIC and the bootstrap. Fits with weights equal fits to the
expanded panels.weights, bootstrap standard errors now draw new frequencies
from Multinomial(sum(w), w / sum(w)) and refit with them in place of the
weights. This equals the bootstrap of the expanded observations (or
panels). Before, rows were resampled with their original weights, which
is a different and much more variable sampling scheme. Bootstrap
standard errors need whole-number weights; use
stderr = "robust" for other weights.model$boot_failures.x and 2 * x are accepted) and matching
random-parameter distributions and correlation. A larger model whose
log-likelihood is materially below the restricted one’s (LR below
-max(0.01, 2e-6 |logLik|)) gives no test, with a reason in
LR_reason, instead of LR = 0. The intercept-only base model
of regCompTest() is not nested in a model without an
intercept. Objects from older versions get no LR test between fitted
models (refit them).engine = "quadrature", the new default of the d/p/q
functions, countreg() and countreg_rp()).
Averaging over 1500 Halton draws was badly biased in the tails: for PGE
with shape 1 (geometric with mean 1) and y = 1000 it gave log P = -3847
instead of -693.8. The new values agree with exact special cases (PGE
with shape 1 and PW with alpha 1 are geometric; P(Y = 0) of PGE is a
beta function) and with independent quadrature to about 1e-9, for counts
up to 1e5. Fits are faster too. engine = "halton" keeps the
earlier method, and objects without a stored engine predict as
before.Simulated predictions with lognormal parameters no longer
need lamW. Exact uses log-scale MGFs and reports an
overflow of a finite expectation as such. For lognormal parameters with
x < 0, Exact uses a Laplace approximation (documented as
approximate).NaN for that element, with one warning (base R’s
convention), and missing parameters NA, at every
q including q < 0 and q = Inf
(before, those endpoints returned 0 or 1).
dgwar()/pgwar() no longer stop for an invalid
element. plindley() computes both tails directly.find_lambda_cpp() honors
its tolerance (relative error of the mean) and iteration limit and
reports non-convergence instead of accepting a collapsed bracket;
find_lambda_diag_cpp() gives the residual, iterations and
status. Unused controls of the internal moment functions were
removed.renb(): the log-likelihood is computed
as three stable differences of log-gamma functions. For large
a and b, terms of size ~1e200 canceled and the
optimizer could report a positive log-likelihood of ~1e203
(changed, fits that hit this
region).renb() standard errors (changed).
renb() now has analytic scores, so its Hessian is the
derivative of an exact gradient. Before, it was a second finite
difference of the log-likelihood, which was inaccurate (it could be
indefinite and give NaN standard errors or delta-method
marginal-effect standard errors, notably for ln(a-1) and
ln(b)). Estimates are unchanged; standard errors can
change.rpardists values are checked before a single value is
expanded.model$fcr_schema).dis_param_formula_2 is an error for them. Predictions from
fits made with earlier versions are unchanged. The
dpge()/dpoisweibull() families of functions
keep their scale arguments.underreport_formula is an error (only exp(b0) * p is
identified), and countreg() warns when the reporting and
count coefficients are nearly collinear (correlation above 0.99), which
happens when reporting is separated from the count mean only by the
curvature of the link function.summary() no longer reports a test against Poisson for PL,
PLG and PLL (which cannot reduce to Poisson: their variance is at least
mu + mu^2 / 2), for NBP, SI, PW, PGE and GW (nonregular restrictions),
or for boundary families with a dispersion formula.
regCompTest() uses the same rules (same estimator and model
components, nested parameters and families), uses a 50:50 chi-square
mixture when one parameter is on the boundary (also with extra mean
covariates), requires two fitted models to use the same observations,
outcome, offsets and weights, returns LR_type, and gives no
p-value (instead of 1) when the larger model has the lower
log-likelihood. The README zero-inflation example now compares models by
AIC and BIC.log argument), so extreme counts keep
finite log-likelihoods (log P(Y = 1000 | mu = 1) = -5913 instead of
log(0)). Rows or panels with zero weight contribute exactly 0.dcom(1000, lambda = 1000, nu = 1) was 0 instead of 0.0126),
one support rule for the PMF, CDF, quantiles and moments, moments
computed from the normalized PMF, and a bracketed solver for the rate
given the mean (accurate to about 1e-8, NaN with a warning when it
fails, instead of silently returning an unconverged value).Chol: labels and the default starting values were built row
by row while the Cholesky factor was filled column by column, so labels
were attached to the wrong elements, named starting values went to the
wrong elements, and the default start was a singular matrix instead of
0.1 * I. Labels, starting values, the likelihood and predictions now use
one packing. Estimates and predictions of earlier fits were internally
consistent; only their labels were wrong.countreg_rp() rejects a variable in both
formula and rpar_formula when its random
parameter is normal, uniform or triangular (only the sum of the fixed
coefficient and the random mean is identified). Lognormal and gamma
random parameters with a fixed shift are still allowed.poly(), splines::ns() and
scale() are evaluated with the training values at
prediction time (a row is predicted the same alone or in any
batch).boot_failures), and the covariance uses the accepted
replicates only (not pairwise deletion).countreg_rp() weights that vary
within a panel are an error (they were silently replaced by the first
weight of the panel).pplind(),
ppinvgaus(), ppinvgamma(),
ppLnorm(), pplindLnorm(),
pplindGamma(), ppge(),
ppoisweibull(), psichel(),
pgwar(), pcom()) follow one contract: NA gives
NA (it gave 0), q < 0 and -Inf give 0, Inf gives 1 (several gave 0 or
failed with “result would be too long a vector”), the upper tail and log
scale follow, and zero-length input gives numeric(0). Small
upper tails are summed directly on the log scale instead of taken as 1 -
CDF.cureplot() uses the rows used in estimation by default,
builds the outcome, predictions and plotting variable with one mask of
complete rows (they could be misaligned after missing values), errors
for an unknown indvar, and passes method only
to random-parameter and negative multinomial models (the default
NULL uses the estimator’s default).log() of a non-positive
value) and of full column rank (aliased columns are named); weights must
be finite with a positive total; start.vals must be finite;
max.iters and ndraws must be whole
numbers.rp_mgf() handles zero-scale
lognormal and gamma coefficients exactly and computes uniform and
triangular MGFs on the log scale.countreg_rp() has a mix_draws argument for
the inner integration of the PLN, PGE, PLL and PW families (default
min(ndraws, 200)), so the cost is proportional to
ndraws * mix_draws instead of ndraws^2.
Scrambled Halton draws are generated from a seed stored in the fit, so
predictions reuse the estimation draws and leave the caller’s random
numbers unchanged.model$fcr_version).DESCRIPTION has BugReports and
the GitHub URL; a CITATION file and a contributor guide
with a release checklist were added; CI also checks the minimum R
version; the slowest stochastic tests are skipped on CRAN.pcom() ignored lower.tail and
log.p. Both tails are now summed directly on the log scale
with a precise normalizing constant, so upper tails are never negative
and keep their relative precision (e.g.
pcom(25, lambda = 1, nu = 1, lower.tail = FALSE) equals the
Poisson value 9.5e-28). Recycling of mu,
lambda and nu in dcom(),
pcom() and qcom() follows the base-R rule
(length 1 or the length of the first argument; other lengths are an
error).dpoisweibull() and friends used lambda
inconsistently between the PMF and the mean; parameters given only
partly now warn instead of failing.NaN (with one warning)
for invalid parameters instead of failing, returning 0, or emitting
extra warnings. Missing inputs give NA.qsichel() returns Inf at p = 1 (it
returned NA with a coercion warning) and NaN
for p outside [0, 1] (it searched 10,000 counts). rsichel()
and rinvgamma() accept a vector n (its length
is used, as in base R).halton_dists() draws one dimension by default, uses the
stated half-width for uniform draws (mean +/- sdev), and
errors for an unknown distribution. corr_haltons() gives
each column its own mean, standard deviation and bounds for truncated
normal draws, and errors for an unsupported distribution,
hdraws with the wrong number of columns, or a Cholesky
factor of the wrong size.confint(), summary() and
tidy() work (with NA standard errors) when a
model has no covariance matrix.bootstraps is checked up front (a single number of at
least 2) instead of failing after the model is fit.. in formulas, and keeps
the contrasts of factors in auxiliary formulas for prediction. Fitted
objects store the expanded formulas, so bootstrap refits of models
written with . work.method = "Nelder-Mead" is accepted by every estimator
as an alias of "NM".qplind() and qplindLnorm() return
NA for missing parameters instead of failing, and
qplindLnorm()/rplindLnorm() accept
sigma = 0 (the Poisson-Lindley limit).regCompTable() fits the baseline model only when the
pseudo-R^2 is requested. tidy() classifies parameters from
the model’s bookkeeping (covariates named like distribution parameters
are no longer misclassified).template: math-rendering: mathjax). The equations of help
pages (\eqn{}, \deqn{}) and articles were
shown as raw LaTeX, for example in ?countreg_mix.?countreg_rp documents each random-parameter
distribution’s scale, the heterogeneity specification and the lognormal
caveat.?renb states that the marginal variance exists only for
a > 2 (it is infinite for the legal values 1 < a <= 2).?washington_roads describes the panel structure; the
Rollover label in the data is corrected. The README
function list is corrected and completed.importFrom(). lamW stays in Suggests (its uses in
qlindley() and lognormal random-parameter predictions are
checked with rlang::check_installed()); dials and parsnip
are added to Suggests.rlindley() draws from the gamma mixture form directly
(no longer needs lamW) and no longer warns for every whole-number
n.src/Makevars and src/Makevars.win are
removed (no OpenMP or BLAS is used), so
SystemRequirements: GNU make is dropped.tests/testthat/test-all.R
and a duplicated test.poilog engine is checked with
rlang::check_installed().msg1 and .dpge_one are no longer exported.
The hand-maintained Collate field is removed.margEffTable(): average marginal effects,
elasticities and, for indicators, pseudo-elasticities or discrete
changes, for every estimator, with delta-method or bootstrap
(independent units, optional cluster_var) standard errors.
Variables that change the expected count only through auxiliary formulas
(underreporting, zero model, random parameters and their heterogeneity,
and distribution parameters when the mean depends on them, as in hurdle
models) are included by default.repois() (random-effects Poisson)
and negmultinom() (negative multinomial NM1, NM2 and NM-P),
with weights, robust and bootstrap standard errors, predictions and the
common methods.countreg()
family, through the new zero_formula and
zero_type arguments (checked against
pscl::zeroinfl() and pscl::hurdle()).predict(type = "prob") (probabilities of each count),
randomized quantile residuals
(residuals(type = "quantile")) and
rootogram().R/families.R), which makes adding a family a one-file
change.predict(method = "Individual") (alias
"EB") for countreg_rp() models now computes
Empirical Bayes observation-specific predictions following Wood and
Gayah (2025), weighting each draw by the likelihood of the unit’s
observed outcomes. Previously it returned the simulated predictions.
Panels are matched to the rows of newdata by id (a
group_var given as a vector is stored as the column
.fcr_panel_id), and the response expression is evaluated as
in estimation. eb_type = "mean" returns the conditional
mean instead of plugging in the conditional coefficients; the
conditional coefficients and their standard deviations are returned as
attributes.predict() gains
type = c("response", "true", "prob_reported", "link") for
countreg() models.countreg() accepts weights as a numeric
vector as well as a column name.countreg.rp() is deprecated; use
countreg_rp(), now the documented name
(?countreg_rp). countreg.rp() still works,
with a once-per-session warning, and returns the same fit.predict(object, data = ...) is deprecated; use
newdata.print.level in renb() and
poisLind.re() is deprecated; use verbose.
panel_id in countreg_rp() is deprecated; use
group_var. The old names still work, with a
once-per-session warning.coef(),
vcov(), logLik(), nobs(),
fitted(), residuals() (response and, for
countreg(), Pearson), confint(),
formula(), terms() and print().
AIC(), BIC() and update() now
work. For panel models, logLik() reports the number of
panels as its nobs, so BIC() uses the number
of independent units.simulate() draws responses from fitted
countreg() models (all families, including
underreporting).vcov()),
and renb(), poisLind.re() and
countreg_rp() gain
stderr = c("normal", "robust", "boot"). Robust standard
errors of panel models are clustered by panel; bootstraps resample whole
panels. countreg_rp() gains bootstraps.keep_data;
keep_data = FALSE does not store the training data.countreg_rp() and poislind_re() are
snake_case names for countreg_rp() and
poisLind.re().AIC() and BIC() replace
myAIC() and myBIC().