Skip to contents

Fits by IRLS on the Rust core. The design matrix is R's own model.matrix(), so formulas, factors (treatment coding) and offset() terms work as in stats::glm(). Results match statsmodels' GLM (validation/scripts/statsmodels_glm.py).

Usage

glm_fit(
  formula,
  data,
  family = "poisson",
  link = NULL,
  offset = NULL,
  weights = NULL,
  dispersion = NULL,
  theta = NULL,
  power = NULL,
  link_power = NULL
)

Arguments

formula

A model formula; offset(...) terms are honoured.

data

A data frame.

family

"gaussian", "poisson", "gamma", "inverse_gaussian", "binomial" (response a proportion, weights the trials), "negative_binomial" (needs theta) or "tweedie" (needs power).

"identity", "log", "logit", "probit", "cloglog", "inverse", "inverse_squared" or "power" (needs link_power); NULL for the log link for the gamma, inverse Gaussian and Tweedie and the canonical link otherwise. R's own glm() defaults to the canonical link (Gamma() is the inverse link), so give link when porting a model from it.

offset

Optional offset added to any offset() terms.

weights

Optional prior weights.

dispersion

NULL (1 for the Poisson, binomial and negative binomial; Pearson's estimate otherwise), "pearson" (with the Poisson, the over-dispersed Poisson, which accepts negative responses as long as the fitted means stay positive), "deviance" or a fixed number.

theta

Negative binomial theta (variance mu + mu^2 / theta).

power

Tweedie power in (1, 2).

Exponent of the power link.

Value

A glm_model with properties coefficients, std_errors, p_values, covariance, dispersion, deviance, null_deviance, log_likelihood, aic, bic (counting the coefficients as aic does; stats::BIC() also counts an estimated dispersion), df_resid, iterations and fitted. Use stats::coef(), stats::predict() and predict_distribution().

Details

The rating variables of Python's Terms are formula terms here: interactions a:b, raw powers poly(x, 3, raw = TRUE), hinges I(pmax(0, x - 30)), steps I(x >= 30), bins cut(x, c(-Inf, 30, 50, Inf)), a centred log log(x / 40) and natural splines splines::ns(x, knots = ...). For an ordered factor in cumulative coding (each coefficient the step from the level below), use one step column per level, I(as.integer(f) >= 2) and so on, on a factor with its levels in order.

Examples

d <- data.frame(claims = c(1, 2, 4, 2, 1, 3), region = c("N", "N", "S", "S", "W", "W"),
                exposure = c(1, 2, 1, 1, 0.5, 1.5))
m <- glm_fit(claims ~ region + offset(log(exposure)), d, family = "poisson")
coef(m)
#>  (Intercept)      regionS      regionW 
#> 1.231682e-16 1.098612e+00 6.931472e-01 
predict(m, data.frame(region = "W", exposure = 2))
#> [1] 4