| semireg | R Documentation |
Fit a semiparametric (additive mixed) model with lme4 (lmer for gaussian, glmer for other families): smooth terms written in the formula, as in mgcv::gam, are fitted as random effects. For negative binomial, zero-inflated or correlated data use semireg_tmb.
semireg(formula, data, family = NULL, REML = TRUE,
control = lmerControl(optimizer = "nloptwrap"),
start = NULL, verbose = FALSE, drop_unused_levels = TRUE, subset, weights,
offset, contrasts = NULL, ...)
formula |
A two-sided linear formula object describing both the fixed-effects and random-effects part of the model, with the response on the left of a ~ operator and the terms, separated by + operators, on the right. Random-effects terms are distinguished by vertical bars ("|") separating expressions for design matrices from grouping factors. |
data |
A data frame or list containing the model response variable and covariates required by the formula. By default the variables are taken from environment(formula), typically the environment from which semireg is called. |
family |
A GLM family (see |
REML |
Logical scalar - Should the estimates be chosen to optimize the REML criterion (as opposed to the log-likelihood)? |
control |
A list (of correct class, resulting from lmerControl() or glmerControl() respectively) containing control parameters, including the nonlinear optimizer to be used and parameters to be passed through to the nonlinear optimizer, see the *lmerControl documentation for details. The default is |
start |
Starting values, as for |
verbose |
Passed on to the lme4 fitting functions. |
drop_unused_levels |
By default unused levels are dropped from factors before fitting. For some smooths involving factor variables you might want to turn this off. Only do so if you know what you are doing. |
subset |
An optional expression indicating the subset of the rows of data that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. |
weights |
An optional vector of <e2><80><98>prior weights<e2><80><99> to be used in the fitting process. Should be NULL or a numeric vector. |
offset |
This can be used to specify an a priori known component to be included in the linear predictor during fitting. This should be NULL or a numeric vector of length equal to the number of cases. One or more offset terms can be included in the formula instead or as well, and if more than one is specified their sum is used. See model.offset. |
contrasts |
An optional list, as |
... |
Further arguments for passing on to model setup routines. Arguments removed in 2.0 ( |
A semiparametric model is fitted as a linear (or generalized linear) mixed model whose random effects are the penalised parts of smooth functions of covariates (Wand and Ormerod, 2008); each smooth's variance is its smoothing parameter, estimated by (RE)ML.
A list of class semireg. print() shows a short account of the fit: the formula as written, the
smooth terms (one row per random-effect block: the smooth, its random-effect term, its covariate, basis, basis
dimension, smoothing variance and whether it is estimated as a straight line), the fixed effects, the other
variance components and any advice. The smooth, term and covariate columns are the values
semipred takes for sm_term and covariate. summary() adds the summary of the fitted
mixed model (summary(fit)$model); tidy(fit) returns the smooth table and tidy(fit, "fixed") the
fixed effects with standard errors. A term fitted as another (te() as t2()) is printed below the
table and kept in attr(tidy(fit), "requested") (the term as written and the call fitted). coef(), fixef(), vcov(), fitted(),
residuals(), logLik(), AIC(), nobs(), family(), VarCorr() and
ranef() work as for the fitted mixed model, and formula() gives the formula as written.
anova() tests the terms and smooths; notes on the fit are in attr(, "advice") (advice).
Its elements:
semer |
The fitted |
call |
The call of |
data |
A data.frame with generated variables in the fitting. |
fomul_vars |
Name of variables in the formula of semireg model. |
sm_vars |
Names of the variables of the smooths. |
cov_lst |
Covariance matrix list for each smooth term. |
u_lst |
Random effects list for each smooth term. |
CovMat |
Covariance matrix for all smooth terms. |
Cov_ind |
Covariance matrix index for each smooth term. |
Cov_indN |
Covariance matrix index for each smooth term of several blocks (e.g. |
df |
Degree of freedom of all random terms. |
lmerc |
Call used in the mer model in the fitting. |
smooths |
For smooths written in the formula: the mgcv smooth objects and the maps that give the random-effect
design of each block for new data (used by |
Smooths can be written in the model formula, as for mgcv::gam, next to fixed and lme4 random terms:
y ~ A + s(x, by = A) + (1 | Block). Each smooth is set up by mgcv (bases, knots, identifiability
constraints) and split, as in gamm4, into an unpenalised part, which is added to the fixed effects as
ordinary terms, and penalised parts, each a block of random effects with one variance. The fixed terms are
added automatically (terms already written are not doubled), so a smooth by a factor cannot lose its group
slopes:
| Written | Meaning | Fixed terms added |
s(x), s(x, bs = "cr", k = 12) | one curve | x |
s(x, by = f) | a curve per level of f, a variance each (id = 1: one shared) | f + f:x |
s(x, by = z), z numeric | varying coefficient f(x) z | z + z:x |
s(x, f, bs = "fs") | random curves per level, one variance | none |
(s(x, k = 10) | g) | random curve per level of g: (x | g) (correlated intercepts and slopes) plus a spline deviation per level, one variance | none |
s(x1, x2) | isotropic surface (thin plate) | x1 + x2 |
s(x, bs = "os", k = 10) | O'Sullivan spline with k interior knots (1.x smZ(x, k = 10)); xt = list(knots = , range = ) sets the interior knots and the range | x |
s(x1, x2, bs = "ztps", k = 6) | low-rank thin plate with k knots (1.x smZ(cbind(x1, x2), type = "Ztps", k = 6)); xt = list(knots = ) sets the knots (a two-column matrix) | x1 + x2 |
s(x, bs = "user", xt = list(basis = f)) | a basis of your own: f(x) (f(x1, x2) for two covariates) returns a matrix with a row per value, whose columns get iid random coefficients with one variance (as a matrix in smoothZ); checked before the fit (see below); xt = list(basis = f, null = "constant") or "none" for a smaller fixed part; xt = list(basis = f, penalty = S) for a penalty of your own (see below) | x (x1 + x2); with a penalty, its null space |
t2(x1, x2), t2(x1, x2, bs = c("cr", "ps"), k = c(6, 8)) | tensor-product surface (covariates on different scales), a variance per penalty; te() is fitted as t2() | x1 + x2 + x1:x2 |
s(x, bs = "cs"), "ts" | shrinkage smooths (no unpenalised part) | none |
s(x, f) | common curve + a deviation curve per level of f, one variance for the deviations | x + f + f:x |
s(x, f1:f2) | the same with the cells of f1:f2 | x + f1:f2 + f1:f2:x |
s(x, f1*f2) | common curve + deviation curves for f1, f2 and f1:f2, a variance each | x + f1*f2 + f1:x + f2:x + f1:f2:x |
s(x1, x2, f) | common surface + a deviation surface per level | x1 + x2 + f + f:x1 + f:x2 |
A factor term among the arguments of s() gives this ANOVA-like split (not an mgcv form): the deviation
curves of a factor term are random effects with one variance, so varcomp() shows how much the curves differ
by f1, by f2 and by their interaction, and a variance of zero means the curves of that term have the
same shape (their levels still differ by the fixed terms). The pieces are set up without constraints between them:
the mixed model separates them by their variances, as nested random effects. Each level's curve is the fixed part
plus the common curve plus its deviations.
A random curve (s(x) | g) (O'Sullivan basis unless bs is given) is the group-specific curve model of
Durban et al. (2005) and Harezlak, Ruppert and Wand (2018, section 9.2): each level of g (a subject) has its
own straight line, (x | g), and its own spline deviation, all levels sharing one variance; e.g. heights of
boys over age, height ~ s(age, bs = "os", k = 20) + (s(age, k = 10) | id). Unlike s(x, g, bs = "fs"),
the intercepts and slopes are correlated, as pdSymm(~ x) in nlme::lme. The random curves are random
effects: semipred() and predictmeans() give the population curves without them, and
anova() tests whether they are needed (their variance is zero: each subject's curve is a straight line).
The fits equal gam(..., method = "REML") for gaussian models (with s(g, bs = "re") for a random
intercept), and semipred() and predictmeans() give the curves, means and their standard errors of
predict.gam(). The variables are used as they are (not centred or scaled). Tensor products: t2(x1, x2) (Wood, Scheipl and Faraway 2013), a surface for covariates on different scales,
whose penalties (one per product of the marginal penalised and unpenalised parts; full = TRUE for more)
are independent random effects, each with its own variance; the fixed terms x1 + x2 + x1:x2 are added,
and by = f gives a surface per level. It is set up without mgcv's sum-to-zero constraint on the whole
product (which leaves a little of the penalised space in the unpenalised one), so its fixed part is exactly those
terms; the fit equals gam() with that basis and its penalties, and gam()'s own t2() when there
are no other random effects. te() is fitted as t2() (with a message): its overlapping penalties
cannot be written as random effects; ti() is not available. Objects named in
s() (e.g. xt = list(knots = kn)) are taken from the environment of the formula.
A basis of your own (bs = "user") must give the same row for the same covariate value whatever data it is
given, as prediction evaluates it on new values: knots and range belong in the function, e.g.
f <- function(x) ZOSull(x, intKnots = c(2, 4, 6, 8), range.x = c(0, 10)). It is checked before the fit, and
the fit stops with what is wrong and how to put it right when it fails on the data, does not return a numeric
matrix with a row per value (also for a single value), gives missing or infinite values, gives different values on
two calls, gives other rows for the same values on part of the data (knots or range taken from the data), or has
columns in the span of its fixed part. Linearly dependent columns, and more columns than observations (a spatial
basis on a field grid with missing plots, e.g. the five blocks of SpATS's PSANOVA, or LVIS), are allowed:
the coefficients are penalised, so the fit stays defined (semireg() only; semireg_tmb() stops for
blocks wider than the data). A dependent column is not neutral: with iid coefficients the curve's covariance is
\sigma_s^2 B B' (B the basis, \sigma_s^2 the smooth's variance), so an extra column (e.g. the
sum of two others) changes the penalty and the fit, as in mgcv::gam() with the same basis. With as many
independent columns as observations or more, the basis can contain the fixed part, which is then not checked:
the fit is defined, but the fixed intercept and slope are confounded with the smooth (use null = "none"
when the basis has them). A basis defined only at the data's points (a lookup on a grid) is fitted, and
semipred(deriv = ) says that slopes are not available. Its values are checked again at prediction.
Without a penalty the basis's coefficients are iid (a ridge penalty, shrinking the curve towards its fixed part).
xt = list(basis = f, penalty = S) gives them the penalty \lambda\beta' S\beta instead (S a
symmetric positive semi-definite matrix, one row and column per basis column), as mgcv::gam(paraPen = ):
e.g. a P-spline from any B-spline basis with S = crossprod(diff(diag(k), differences = 2)). The penalty's
null space (functions it leaves alone: the straight line for second differences, the constant for first, the
quadratic for third; larger or non-polynomial null spaces stop) is then
the smooth's fixed part, found from the basis as for the mgcv smooths, so xt$null must be left out or
"none". The basis then has no columns removed: a B-spline basis spans the constant, which the penalty's
null space and the model's intercept share (as s(x, bs = "ps")).
The penalised-spline examples fitted by nlme::lme in Wand's course scripts and in HRW (additive
models, additive mixed models, thin-plate surfaces with given knots, group-specific curves with a contrast curve)
give the same REML log-likelihood and fitted values with semireg() (tests/testthat/test-semireg-golden.R);
their data are in the package: growthIndiana, SBMDfem, ozoneCalif,
scallop, wageTUnion, copper, whose help pages show the analyses.
The optimizer is nloptwrap (lme4's default for lmer) for gaussian fits since 2.0: on these
examples it reached the same optimum as bobyqa (1.x's default) faster. Generalized fits use
bobyqa unless control is given: with nloptwrap they often failed lme4's convergence check,
which semireg() runs as lmer() and glmer() do (the result is in
fit$semer@optinfo$conv$lme4, reported by pm_check() and advice()). Each smooth block of a formula smooth is scaled as a random intercept (sum of
squares equal to the number of observations), so that the optimizer starts near the optimum; the variance of a
smooth block reported by VarCorr() or varcomp() is on that scale.
Moving from 1.x: smZ() and smoothZ are superseded and were removed in 2.0 (they stop with a pointer to the formula syntax); vignette("migrating") shows each
smoothZ = list(sm = smZ(...)) form beside its formula form, which gives the same fit (checked in
dev/check-smz-migration.R). The variables are no longer centred (1.x's ncenter = TRUE), which put knots
given in the data's units (smZ(x, intKnots = )) in the wrong place.
Dongwen Luo, Siva Ganesh and John Koolaard
Durban, M., Harezlak, J., Wand, M.P. and Carroll, R.J. (2005). Simple fitting of subject-specific curves for longitudinal data. Statistics in Medicine, 24, 1153-1167.
Harezlak, J., Ruppert, D. and Wand, M.P. (2018). Semiparametric Regression with R. Springer, New York.
Wand, M.P. and Ormerod, J.T. (2008). On semiparametric regression with O'Sullivan penalized splines. Australian and New Zealand Journal of Statistics. 50, 179-198.
Wood, S.N., Scheipl, F. and Faraway, J.J. (2013). Straightforward intermediate rank tensor product smoothing in mixed models. Statistics and Computing, 23, 341-360.
semireg_tmb, anova.semireg, semipred, varcomp, predictmeans
library(predictmeans)
## 1. Curves in a mixed model (nlme::Dialyzer): a curve of the ultrafiltration rate over
## pressure for each blood flow rate, a random intercept and slope per dialyzer; the
## fixed terms QB + QB:pressure are added automatically
data(Dialyzer, package = "nlme")
fm <- semireg(rate ~ s(pressure, by = QB, bs = "os", k = 4) + (pressure | Subject),
data = Dialyzer)
anova(fm) # fixed effects (Kenward-Roger df) and a likelihood ratio test of each smooth
varcomp(fm) # variance components, the smooths' among them
predictmeans(fm, "QB", covariate = c(pressure = 1))$means
semipred(fm, "QB", "pressure", contr = c("300", "200"), band = "simultaneous")$plt
## 2. A designed experiment: treatments on the whole plots of six blocks, curves over time;
## treatment means at a time get Satterthwaite df from the whole-plot stratum
set.seed(11)
sp <- expand.grid(t = 0:10, A = factor(c("a1", "a2", "a3")), Block = factor(1:6))
sp$y <- 2 + sin(sp$t/2) + 0.08*(sp$A == "a2")*sp$t + rnorm(6, 0, 0.5)[sp$Block] +
rnorm(18, 0, 0.3)[interaction(sp$Block, sp$A)] + rnorm(nrow(sp), 0, 0.3)
fsp <- semireg(y ~ s(t, by = A, bs = "os", k = 6) + (1 | Block) + (1 | Block:A),
data = sp)
predictmeans(fsp, "A", covariate = c(t = 5), pairwise = TRUE)$pairs
## 3. Two crossed factors: a common curve and deviation curves for f1, f2 and f1:f2, each
## with its own variance; which deviations are needed?
set.seed(1)
dx <- expand.grid(x = seq(0, 1, length = 15), f1 = factor(c("p", "q")), f2 = factor(c("u", "v")),
rep = 1:3)
dx$y <- sin(2*pi*dx$x) + (dx$f1 == "q")*sin(pi*dx$x)^2 + rnorm(nrow(dx), 0, 0.2)
fx <- semireg(y ~ s(x, f1*f2, bs = "os", k = 6), data = dx)
varcomp(fx, test = TRUE)
## 4. An additive model with a varying coefficient: a smooth in x1, and the effect of z
## changing smoothly with x2 (numeric 'by')
set.seed(2)
da <- data.frame(x1 = runif(200), x2 = runif(200), z = rnorm(200))
da$y <- sin(3*da$x1) + da$z*sin(2*pi*da$x2) + rnorm(200, 0, 0.3)
fa <- semireg(y ~ s(x1, bs = "os") + s(x2, by = z, bs = "os"), data = da)
anova(fa)$smooth
## 5. A basis of your own (checked before the fit): a seasonal cycle on a straight trend
set.seed(3)
ds <- data.frame(day = 1:730)
ds$y <- 10 + 0.002*ds$day + 2*sin(2*pi*ds$day/365) + rnorm(730)
season <- function(d) cbind(sin(2*pi*d/365), cos(2*pi*d/365), sin(4*pi*d/365), cos(4*pi*d/365))
fs <- semireg(y ~ day + s(day, bs = "user", xt = list(basis = season, null = "none")),
data = ds)
semipred(fs, covariate = "day")$plt
## 6. A tensor-product surface for two covariates on different scales (data(ozoneCalif)),
## and a curve in a third
data(ozoneCalif)
fo <- semireg(ozone ~ t2(inversion.base.height, inversion.base.temp) +
s(daggett.pressure.gradient, bs = "os", k = 15), data = ozoneCalif)
anova(fo)$smooth # a variance per penalty of the surface
semipred(fo, covariate = c("inversion.base.height", "inversion.base.temp"))$plt
## 7. Binary responses with a random intercept per child (HRW::indonRespir): the probability
## of a respiratory infection over age
if (requireNamespace("HRW", quietly = TRUE)) {
data(indonRespir, package = "HRW")
fb <- semireg(respirInfec ~ s(age, bs = "os", k = 10) + vitAdefic + female + height + stunted +
visit2 + visit3 + visit4 + visit5 + visit6 + (1 | idnum),
family = binomial, data = indonRespir)
semipred(fb, "age", "age")$plt
}
## 8. Subject-specific curves: each subject's own straight line, (Days | Subject), and its
## own spline deviation, one variance for all; are the subjects' curves straight lines?
fr <- semireg(Reaction ~ s(Days, bs = "os", k = 4) + (s(Days, k = 4) | Subject),
data = lme4::sleepstudy)
anova(fr)$smooth
## 9. Curves by group, the price of apartments in Warsaw by district (HRW::WarsawApts)
if (requireNamespace("HRW", quietly = TRUE)) {
data(WarsawApts, package = "HRW")
WarsawApts$district <- factor(WarsawApts$district)
fw <- semireg(areaPerMzloty ~ s(construction.date, by = district, bs = "os", k = 15),
data = WarsawApts)
semipred(fw, "district", "construction.date", contr = c("Srodmiescie", "Mokotow"))$plt
predictmeans(fw, "district", covariate = c(construction.date = 1980))$means
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.