Package {predictmeans}


Version: 2.0.0
Title: Predicted Means for Linear and Semiparametric Models
Description: Predicted means, standard errors, contrasts, multiple comparisons, permutation and bootstrap tests, R-squared and diagnostics for models fitted by 'aov', 'lm', 'glm', 'gls', 'lme', 'lmer', 'glmer', 'glmmTMB', 'gam' and 'semireg'. Defaults are chosen on evidence: Kenward-Roger degrees of freedom and adjusted standard errors for REML 'lmer' fits (Kenward and Roger (1997) <doi:10.2307/2533558>), permutation p-values (b+1)/(B+1), stratum standard errors for 'aov' models with Error() terms as in 'Genstat', and equal-weight means over observed cells with a warning. Results are tested against 'SAS' PROC MIXED and 'Genstat' output and the 'pbkrtest', 'nlme' and 'emmeans' packages. Functions stop with a message rather than return a wrong result, give one-line advice triggered by the data, and give the same resampling results for any number of cores.
Depends: R (≥ 3.6.0), lme4, nlme
Imports: glmmTMB, ggplot2 (≥ 3.4.0), graphics, grDevices, grid, Matrix, MASS, methods, mgcv, numDeriv, parallel, stats, utils
Suggests: ordinal, car, reformulas, TMB, lmerTest, emmeans, generics, marginaleffects, mvtnorm, HRW, pbkrtest, plotly, testthat (≥ 3.0.0), knitr, rmarkdown
Config/testthat/edition: 3
License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]
URL: https://dongwenluo.github.io/predictmeans/, https://github.com/dongwenluo/predictmeans, https://CRAN.R-project.org/package=predictmeans
VignetteBuilder: knitr
BugReports: https://github.com/dongwenluo/predictmeans/issues
LazyLoad: yes
NeedsCompilation: no
Encoding: UTF-8
ByteCompile: true
Config/roxygen2/version: 8.1.1
Config/Needs/website: tidyverse, gridExtra, DT, gt, summarytools, eda4treeR, Ecdat, HRW, car
Packaged: 2026-11-24 09:27:46 UTC; luod
Author: Dongwen Luo [aut, cre], Siva Ganesh [aut], John Koolaard [aut], James Curran [aut]
Maintainer: Dongwen Luo <dongwen.luo@agresearch.co.nz>
Repository: CRAN
Date/Publication: 2026-11-24 13:20:02 UTC

Predicted Means for Linear and Semiparametric Models

Description

predictmeans logo

This package provides functions to diagnose and make inferences from linear, generalized linear, mixed and semiparametric models, such as those obtained from 'aov', 'lm', 'glm', 'gls', 'lme', 'lmer', 'glmer', 'glmmTMB', 'gam' and 'semireg'. Inferences include predicted means and standard errors, contrasts, multiple comparisons, permutation tests, adjusted R-square and graphs (autoplot()). Vignettes (browseVignettes("predictmeans")) show worked examples. For AI assistants and scripted use, system.file("llms-context.md", package = "predictmeans") gives a compact description of the result tables, defaults and common recipes.

Details

Package: predictmeans
Type: Package
License: GPL (>= 2)

Workflow

From a fitted model to the report: diagnostics, tests, means and contrasts, variance components, then tables and plots

What predictmeans aims for

Author(s)

Dongwen Luo, Siva Ganesh, John Koolaard and James Curran

Maintainer: Dongwen Luo <dongwen.luo@agresearch.co.nz>

References

Welham, S., Cullis, B., Gogel, B., Gilmour, A., & Thompson, R. (2004), Prediction in linear mixed models, Australian and New Zealand Journal of Statistics, 46(3), 325-347.

See Also

predictmeans, autoplot.predictmeans, tidy.predictmeans, advice, pm_check


ATP Content of Preserved Dog Hearts

Description

Data from an experiment to study the effects of preserving liquids on the enzyme content of dog hearts. There were 23 hearts and two treatment factors, A and B, each at two levels. Measurements were made of ATP as a percentage of total enzyme in the heart, at one and two hourly intervals during a twelve hour period following initial preservation.

Usage

data(ATP)

Format

A data frame with 230 rows (23 hearts, 10 times) and 5 columns:

heart

factor, 23 dog hearts.

time

factor, time of measurement (hours after preservation; 10 levels).

A

factor, treatment A (2 levels).

B

factor, treatment B (2 levels).

ATP

ATP as a percentage of total enzyme in the heart (%).

Examples

data(ATP)
fm <- lmer(ATP ~ A*B*time + (1|heart), data = ATP)
predictmeans(fm, "A:B", pairwise = TRUE)$means

Body Length of Beetles (Simulated)

Description

Simulated body lengths of beetles reared in containers within populations, under two treatments in two habitats, of the kind used by Nakagawa and Schielzeth (2013) to illustrate R^2 for mixed models. Used in the R2_glmm vignette.

Usage

data(Body_length)

Format

A data frame with 960 rows and 6 columns:

Population

factor, 12 populations.

Container

factor, 120 containers (nested in populations).

Sex

factor, Female or Male.

Habitat

factor, A or B.

Treatment

factor, Cont or Exp.

BodyL

numeric, body length.

References

Nakagawa, S. and Schielzeth, H. (2013), A general and simple method for obtaining R^2 from generalized linear mixed-effects models. Methods in Ecology and Evolution, 4, 133–142.

Examples

data(Body_length)
fm <- lmer(BodyL ~ Treatment + Habitat + Sex + (1|Population/Container), data = Body_length)
R2_model(fm)

California Test Score Data

Description

Test scores, school characteristics and student demographics of 420 school districts in California, 1998-1999 (kindergarten to grade 6 or 8), as used by Stock and Watson (2007) and in package Ecdat. The data of the semiparametric example with several smooth terms and two random intercepts in the overview article (vignettes/articles/overview.Rmd).

Usage

data(Caschool)

Format

A data frame with 420 rows and 17 columns:

distcod

district code.

county

county (a factor with 45 levels).

district

district (a factor).

grspan

grade span of the district: "KK-06" or "KK-08".

enrltot

total enrollment.

teachers

number of teachers.

calwpct

percentage of students qualifying for CalWORKs (income assistance).

mealpct

percentage of students qualifying for a reduced-price lunch.

computer

number of computers.

testscr

average test score (the mean of readscr and mathscr).

compstu

computers per student.

expnstu

expenditure per student.

str

student-teacher ratio.

avginc

district average income (in USD 1000).

elpct

percentage of English learners.

readscr

average reading score.

mathscr

average math score.

Source

California Department of Education, data of 1998-1999; package Ecdat (Croissant and Graves), data set Caschool.

References

Stock, J. H. and Watson, M. W. (2007). Introduction to Econometrics, 2nd edition. Addison-Wesley, chapters 4-7.

Examples

data(Caschool)
Caschool$log.avginc <- log(Caschool$avginc)

# math scores against three covariates, each a smooth curve, with random
# intercepts for counties and grade spans
fit <- semireg_tmb(mathscr ~ s(calwpct, bs = "os", k = 12) + s(log.avginc, bs = "os", k = 5) +
                     s(compstu, bs = "os", k = 12) + (1 | county) + (1 | grspan), data = Caschool)
semipred(fit, covariate = "log.avginc")$plt


Multicentre Clinical Trial of a Skin Treatment

Description

Favourable responses in a multicentre randomized clinical trial of a topical drug against a control (Beitler & Landis 1985, Biometrics).

Usage

data(Clinical)

Format

A data frame with 16 rows and 4 columns:

Clinic

factor, 8 centres.

Treatment

factor, control or drug.

Favorable

number of patients with a favourable response.

Total

number of patients in the clinic and treatment group.

Source

Beitler, P. J. and Landis, J. R. (1985). A mixed-effects model for categorical data. Biometrics, 41, 991-1000.

Examples

data(Clinical)
gm <- glmer(cbind(Favorable, Total - Favorable) ~ Treatment + (1|Clinic),
            family = binomial, data = Clinical)
predictmeans(gm, "Treatment")$means   # probability scale

Cook's Distances of a Linear (Mixed) Model

Description

Cook's distances of the observations (or groups of observations) of a model fitted by aov, lm, glm, gls, lme, lmer, glmer, glmmTMB or mgcv::gam, with a plot.

Usage

CookD(model, group=NULL, plot=TRUE, id=3, ...)

Arguments

model

Model object returned by aov (without Error()), lm, glm, gls, lme, lmer, glmer, glmmTMB or gam.

group

Optional name (in "quotes") of a variable whose levels are deleted one at a time (e.g. the clusters of a mixed model); the default NULL deletes single observations.

plot

TRUE (the default): draw the distances (ggplot2, as the Cook's distance panel of residplot).

id

The number of the largest Cook's distances labelled in the plot (idn before 2.0, now as in residplot). The default value is 3.

...

Not used: idn, newwd (before 2.0) stop with their 2.0 spelling.

Details

Cook's distance of an observation (or of a group of observations, group) is D = (\hat\beta - \hat\beta_{(-i)})' V^{-1} (\hat\beta - \hat\beta_{(-i)}) / p, where \hat\beta_{(-i)} are the fixed effects of the model refitted without it, V the covariance of \hat\beta and p their number (for a gam, the effective degrees of freedom, as mgcv's cooks.distance(); the smoothing parameters are re-estimated for each deletion). For lm and aov models and single observations this is the exact closed form of stats::cooks.distance(). Other models are refitted for each deletion: exact also for glm (stats::cooks.distance() for a glm is a one-step approximation), and for mixed models and gls fitted by maximum likelihood (the REML criterion changes with the fixed effects). A deletion that leaves a coefficient without data gives NA. Refitting a generalized linear mixed model for every observation takes time; group deletes whole clusters, usually the more useful check for mixed models.

Value

Invisibly, the Cook's distances (named by observation or group).

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

residplot, pm_check

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)
CookD(fm)
CookD(fm, group = "Block")   # delete whole blocks

Heights of Trees: 37 Seedlots at 6 Sites

Description

Mean heights of 37 seedlots (26 Acacia, Allocasuarina and Casuarina species) grown at six sites in Thailand, the data of Table 5.2 of Williams, Matheson and Harwood, used there for a regression of each seedlot on the site mean (Finlay-Wilkinson regression). 30 site-seedlot combinations have no height.

Usage

data(DataExam5.2)

Format

A data frame with 222 rows and 4 columns:

site

factor, 6 sites.

seedlot

factor, 37 seedlot numbers.

ht

height (cm); NA when the seedlot was not measured at the site.

sitemean

the mean of ht at the site (one value per site).

Details

sitemean takes one value per site, so in ht ~ site + sitemean * seedlot it is aliased with site (its coefficient is NA); see the section "Covariates aliased with a factor" of predictmeans. On the four sites and 27 seedlots with complete data (and sitemean recomputed for them) predictmeans() reproduces the means and slopes of the book's Table 5.7 (tests/testthat/test-level-covariate.R).

Source

Williams, E. R., Matheson, A. C. and Harwood, C. E. Experimental Design and Analysis for Tree Improvement, 3rd edition. CSIRO Publishing, Table 5.2.

Examples

data(DataExam5.2)
fit <- lm(ht ~ site + sitemean * seedlot, data = DataExam5.2)
head(predictmeans(fit, "seedlot", plot = FALSE)$mean_table)
# each seedlot averaged over the sites where it was measured
head(predictmeans(fit, "seedlot", plot = FALSE, weights = "cells")$mean_table)

Potency of Analgesic Drugs in Mice

Description

Data for the comparison of the effectiveness of three analgesic drugs to a standard drug, morphine (Finney, Probit analysis, 3rd Edition 1971, p.103). 14 groups of mice were tested for response to the drugs at a range of doses.

Usage

data(Drug)

Format

A data frame with 14 rows and 5 columns:

Drug

factor, 4 drugs (Morphine, Amidone, ...).

Dose

dose (units as in Finney, 1971).

N

number of mice in the group.

R

number of mice responding.

log10Dose

log10(Dose).

Source

Finney, D. J. (1971). Probit Analysis, 3rd edition. Cambridge University Press, p. 103.

Examples

data(Drug)
gm <- glm(cbind(R, N - R) ~ Drug + log10Dose, family = binomial(link = "probit"), data = Drug)
predictmeans(gm, "Drug", covariate = c(log10Dose = 0.5))$means

Matrix of Coefficients in a Linear Model

Description

This function obtains a matrix of coefficients (the linear functions K such that the predicted means are K\hat\beta) for models such as aov, lm, glm, gls, lme, lmer, glmer, glmmTMB, gam (package mgcv) and semireg.

The predicted means are built on a reference grid: every combination of the factor levels in the model, with covariates fixed at their means (or other chosen values). Each row of K is the average of the grid rows (weighted as weights says; equal by default) for one level combination of modelterm. Combinations of nested factors that cannot exist (a term of the model holds both factors, e.g. G/T, and each level of one occurs with one level of the other) are left out of the averages; so are, with weights = "equal", the empty cells of interaction terms (see predictmeans). When a mean cannot be estimated because two factors that share no term of the model are confounded in the data (not all their combinations occur: a factor nested in another only in the data, each pasture on one farm), the combinations of those two factors without data are left out as well, with a warning that names them: the mean is the average over the combinations that exist. The pair is found by trying, pairs among the factors averaged over first. Writing the nesting in the formula (G/T) or leaving out the aliased factor gives the same means; weights = "cells" weights the combinations by their numbers of observations. The design matrix of the grid is evaluated with the model's own stored basis information, so covariates may enter the model through transformations such as poly(x, 2), ns(x, 3), bs(x), log(x), scale(x) or I(x^2), only through interactions (e.g. A:x without x, or x:z), or through smooth terms (s(x), te(x, z), s(x, by = A)) of a gam.

Usage

Kmatrix(model, modelterm, covariate=NULL, at=NULL, data=NULL, cov_reduce=mean,
        exclude=NULL, weights=c("equal", "proportional", "outer", "cells", "flat"),
        refgrid=FALSE, ...)

Arguments

model

A fitted model: aov, lm, glm, gls, lme, lmer, glmer, glmmTMB, gam/bam (package mgcv; for gamm use its $gam component) or semireg.

modelterm

Name (in "quotes") of the variables whose combinations give the rows of K: fixed-effect variables of the model joined by ":", e.g. "A" or "A:B". It need not be a term of the model: any combination of its factors can be asked for (e.g. "A:B" for y ~ A + B), and a covariate may be among them (its values as given in covariate, else its mean). A factor created in the model formula, e.g. factor(dose), can be given either as "factor(dose)" or as "dose".

covariate

The values of covariates; those not mentioned are at their means (see cov_reduce).

  • A named list (or named numeric vector) of values, e.g. list(x = c(-1, 0, 1), z = 0.3): a covariate with one value is fixed there; one with several values gives rows of K for each value (all combinations for several such covariates). A data frame gives joint points: one set of rows for each of its rows.

  • An unnamed numeric vector with one value for each covariate of the model, in the order they have in the model. With another length this is an error (before 2.0 the values were recycled, and names were ignored).

  • The name of one or more covariates, in which case predictions are made over a range of values of those covariates (see at).

For a semireg model this may also be a covariate that only appears in the smooth terms.

at

Values for the covariate(s) named in covariate (covariateV before 2.0). For one covariate, a numeric vector. For several covariates, either a list of numeric vectors (all combinations are used; named by covariate, or in the order of covariate) or a matrix with one named column per covariate, where each row is one prediction point (e.g. a set of locations for a two-dimensional smooth). When at is NULL, 50 (one covariate) or 30 (several covariates) equally spaced values over the observed range are used.

data

In some cases, you need to provide the data set used in model fitting, for example when the data used to fit the model can no longer be found. Usually the data are recovered from the model.

...

Not used: arguments removed in 2.0 (covariateV, prtnum) stop with their 2.0 spelling.

cov_reduce

How covariates that are not varied are handled. A function returning a single value, applied to each covariate (the default mean; median is another choice), or the string "average", which averages the predictions over the observed values of those covariates instead of fixing them at one value. With "average", nonlinear terms such as poly(x, 2) or s(x) are averaged over the data, which for a gam gives predicted means adjusted for (rather than evaluated at the centre of) a spatial or temporal trend.

exclude

For gam models only: labels of smooth terms to leave out of the predictions (their columns of K are set to zero), e.g. "s(Block)". The default NULL excludes random-effect smooths (bs = "re" and bs = "fs"), so the predicted means are population-level means, as for lmer. Use exclude = character(0) to keep all smooth terms.

weights

How the cells of the factors that are not in modelterm are weighted when averaging over them: "equal" (the default; equal weights), "proportional" (weights proportional to the frequencies of those cells in the data, the same for every mean, as SAS LSMEANS / OM), "outer" (products of each factor's own frequencies), "cells" (each mean weights the cells by their own frequencies) or "flat" (equal weights over the non-empty cells). The definitions are those of emmeans.

refgrid

Return the grid of all combinations (element refgrid)? The default FALSE builds it only when it is needed (semireg models, means over empty cells). Otherwise each group of variables that share a model term is averaged on its own grid, which gives the same K and is much smaller when factors do not interact: for y ~ Line + Block + Site with 300, 90 and 4 levels, grids of 300, 90 and 4 rows instead of 108,000.

Value

K

Coefficients matrix. It has an attribute "estimable", a logical vector with one value per row that is FALSE for rows that are not estimable functions of the model parameters (e.g. means for a missing cell in a rank-deficient model).

fctnames

A model frame contains factor(s) info in the model.

response

The name of response variable in the model.

preddf

The data of the predictor variables used in model fitting.

refgrid

NULL, or (see argument refgrid) the reference grid of all combinations: a list with the grid data (grid), the sparse weight matrix W that averages grid rows into rows of K, and the rows of fctnames (target), and basis, the function that gives the model's basis for grid rows. Any other basis evaluated on grid, e.g. the smooth terms of a semireg model, can be averaged in the same way as W %*% basis.

empty_cells

NULL, or when some means average over empty cells (weights = "equal"; see predictmeans): affected, which rows of K do so, missing, the empty cells, and compare(C, together = FALSE), which gives comparisons C (rows over the rows of K) on the cells their means have in common (together = TRUE: the cells common to all the means of C).

Author(s)

This function heavily depends on the codes from package "lsmeans".

References

Welham, S., Cullis, B., Gogel, B., Gilmour, A., & Thompson, R. (2004), Prediction in linear mixed models, Australian and New Zealand Journal of Statistics, 46(3), 325-347.

See Also

predictmeans, contrast_family, specify_contrast

Examples

  library(predictmeans)
  data(Oats, package="nlme")
  fm <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)
  Kmatrix(fm, "Variety")$K
  Kmatrix(fm, "Variety", 0.5)$K
  Kmatrix(fm, "Variety", "nitro")$K
  Kmatrix(fm, "Variety", "nitro", at=seq(0, 0.6, 0.1))$K
  Kmatrix(fm, "Variety", list(nitro = c(0, 0.3, 0.6)))$K      # the same, values by name
  # not a term of the model
  Kmatrix(lm(yield ~ Block + Variety + nitro, data=Oats), "Block:Variety")$fctnames

  # Covariates entering through transformations or only through interactions
  fm2 <- lm(yield ~ Block + Variety + poly(nitro, 2), data=Oats)
  Kmatrix(fm2, "Variety")$K
  fm3 <- lm(yield ~ Variety + Variety:nitro, data=Oats)
  Kmatrix(fm3, "Variety", "nitro", at=c(0, 0.3, 0.6))$K

  # A smooth term in an mgcv model, averaged over the observed nitro values
  if (requireNamespace("mgcv", quietly = TRUE)) {
    fm4 <- mgcv::gam(yield ~ Variety + s(nitro, k = 4) + s(Block, bs = "re"), data = Oats)
    Kmatrix(fm4, "Variety", cov_reduce = "average")$K
  }

Level Plot of a Matrix of p-values

Description

Plots the p-values of pairwise comparisons as a square grid of tiles, one for each pair of levels, like a correlation plot: the lower triangle only, the tiles coloured by the size of the p-value.

Usage

PMplot(pmatrix, conf_level=0.95, mtitle=NULL, xylabel=NULL, values=FALSE, basesz=12, ...)

Arguments

pmatrix

A matrix with p-values from pairwise comparisons (the lower triangle is used), or a list of such matrices (e.g. p_valueMatrix of predictmeans with atvar), which are drawn as one square panel each, titled by the list's names (the levels of atvar).

conf_level

The p-values below 1 - conf_level are highlighted (level = 0.05 before 2.0). With the default 0.95 the tiles show four bands (up to 0.01, 0.05, 0.1 and above); with any other value two (up to 1 - conf_level and above).

mtitle

The main title in the graph.

xylabel

The x and y labels in the graph: one for each row of the matrix (or of the list's matrices together). The default uses the row names of the matrix, else the row numbers.

...

Not used: level, margin, legendx, newwd (before 2.0) stop with their 2.0 spelling. (ggplot2 sizes the margins. The legend always lists every band, in the order of the p-values; it sits in the empty upper triangle of a single matrix of 6 or more rows, otherwise to the right of the plot.)

values

Whether to print each p-value on its tile (the default is FALSE). Useful for up to about 15 levels.

basesz

The base font size. The default is 12.

Value

A ggplot object (invisibly NULL when the matrix has no pair of levels). Printing it draws the plot; it can be changed with the usual ggplot2 functions. Before 2.0 the plot was drawn with base graphics and nothing was returned: inside a function or a loop, wrap the call in print().

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

predictmeans, autoplot.predictmeans

Examples

  library(predictmeans)
  set.seed(2013)
  pvalues <- runif(28)
  pmatrix <- matrix(0,8,8)
  pmatrix[lower.tri(pmatrix)] <- pvalues
  round(pmatrix, 4)
  PMplot(pmatrix)
  PMplot(pmatrix, values = TRUE)

  Oats$nitro <- factor(Oats$nitro)
  fm <- lmer(yield ~ nitro*Variety+(1|Block/Variety), data=Oats)
  predictout <- predictmeans(fm, "nitro:Variety", atvar="Variety", adj="BH")
  PMplot(predictout$p_valueMatrix)

Egg Counts of Beetles (Simulated)

Description

Simulated egg counts of individual female beetles in containers within populations, under two treatments in two habitats, of the kind used by Nakagawa and Schielzeth (2013). Used in the R2_glmm vignette for a Poisson GLMM with an individual-level (overdispersion) random effect.

Usage

data(Poisson_ind)

Format

A data frame with 480 rows and 7 columns:

Population

factor, 12 populations.

Container

factor, 60 containers (nested in populations).

Sex

factor, Female only.

Habitat

factor, B or A.

Treatment

factor, Exp or Cont.

Egg

integer, number of eggs.

individual

factor, individual within container.

References

Nakagawa, S. and Schielzeth, H. (2013), A general and simple method for obtaining R^2 from generalized linear mixed-effects models. Methods in Ecology and Evolution, 4, 133–142.

Examples

data(Poisson_ind)
gm <- glmer(Egg ~ Treatment + Habitat + (1|Population/Container) + (1|individual:Container),
            family = poisson, data = Poisson_ind)
R2_model(gm)
R2_model(gm, over_disp = TRUE)   # without the overdispersion term

R-squared of a Model as Numbers

Description

The R-squared of a model as a numeric result, for every model class of predictmeans. method = "piepho" (the default) gives the same values as R2_glmm() of predictmeans 1.x (removed in 2.0; Piepho, 2023), as proportions: total, fixed, random and each random-effect component. method = "nakagawa" gives the marginal (fixed effects) and conditional (fixed and random effects) R-squared of Nakagawa and Schielzeth (2013), with random slopes as Johnson (2014): the variance of each random-effect term is the mean of z_i' \Sigma z_i over the observations.

Usage

R2_model(model, method = c("piepho", "nakagawa"), over_disp = FALSE)

Arguments

model

A model of any class predictmeans handles: lm, aov (also with Error()), glm, gls, lme, lmer, glmer, glmmTMB, gam or a semireg fit.

method

"piepho" (every class) or "nakagawa" (lmer, glmer, glmmTMB and lme; for lme with a variance or correlation structure the observation-level variance is the mean residual variance).

over_disp

For "piepho" with lmer, glmer and glmmTMB models: TRUE leaves an observation-level random effect (one level per observation, modelling overdispersion) out of the random share; the model must have one. Default FALSE.

Details

Piepho's R-squared is one definition for every class: the variance of the fixed part of the model (less the bias from estimating the coefficients) and of the random effects, as shares of the average variance of the data. For models without random effects (lm, aov, glm, gls) Total equals Fixed and Random is 0; for lm and aov it is the usual adjusted R-squared. glm models are measured on the link scale (working variances; the latent distribution for a binary response); gls and lme models with any correlation and variance structure; aov models with Error() from the stratum variance components of varcomp. In gam models the smooths are part of the fixed share, except random-effect smooths (bs = "re").

For "nakagawa" the observation-level variance is the residual variance for gaussian models and the variance of the latent distribution for binomial models: \pi^2/3 (logit), 1 (probit) or \pi^2/6 (cloglog). Other families have several competing approximations; use method = "piepho" for them.

Value

A named numeric vector of proportions (class "pm_r2", printed as percentages). For "nakagawa", Marginal and Conditional, with attribute "variances": the fixed-effect, random-effect and observation-level variances. The Nakagawa values agree with performance::r2_nakagawa() (‘tests/testthat/test-r2-model.R’). Notes on the choice of method are kept in attr(, "advice") (advice).

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Piepho, H.-P. (2023), An adjusted coefficient of determination (R2) for generalized linear mixed models in one go, Biometrical Journal, 65(7), 2200290.

Nakagawa, S. and Schielzeth, H. (2013), A general and simple method for obtaining R2 from generalized linear mixed-effects models, Methods in Ecology and Evolution, 4, 133-142.

Johnson, P. C. D. (2014), Extension of Nakagawa & Schielzeth's R2GLMM to random slopes models, Methods in Ecology and Evolution, 5, 944-946.

See Also

varcomp, advice

Examples

  library(predictmeans)
  fm <- lmer(Reaction ~ Days + (Days | Subject), data = sleepstudy)
  R2_model(fm)
  R2_model(fm, "nakagawa")
  R2_model(lm(Reaction ~ Days, data = sleepstudy))   # the adjusted R-squared
  R2_model(glm(breaks ~ wool*tension, family = poisson, data = warpbreaks))

Spinal Bone Mineral Density of Girls

Description

Repeated measurements of spinal bone mineral density of 230 girls and young women aged 9 to 26 of four ethnic groups, from a study of bone mineral acquisition (Bachrach et al. 1999); the data of M. P. Wand's additive mixed model example (gamm()). HRW::femSBMD is a larger version (1003 measurements).

Usage

data(SBMDfem)

Format

A data frame with 547 rows and 7 columns:

idnum

identification number of the subject.

spnbmd

spinal bone mineral density (g/cm^2).

age

age (years).

ethnicity

factor: Asian, Black, Hispanic, White.

black, hispanic, white

indicators (1 = yes) of the ethnic groups other than Asian.

Source

Bachrach, L. K., Hastie, T., Wang, M.-C., Narasimhan, B. and Marcus, R. (1999). Bone mineral acquisition in healthy Asian, Hispanic, Black, and Caucasian youth: a longitudinal study. Journal of Clinical Endocrinology and Metabolism, 84, 4702-4712.

Examples

data(SBMDfem)
SBMDfem$idnum <- factor(SBMDfem$idnum)
# a curve over age, ethnicity as a fixed effect, a random intercept per girl
fit <- semireg(spnbmd ~ s(age, bs = "os", k = 15) + ethnicity + (1 | idnum), data = SBMDfem)
anova(fit)       # ethnicity: F test with Kenward-Roger df; the smooth: likelihood ratio test
# the ethnic groups at age 15, compared in pairs
predictmeans(fit, "ethnicity", covariate = c(age = 15), pairwise = TRUE, adj = "tukey")$pairs
# growth of bone density: where is the curve rising?
attr(semipred(fit, "age", "age", deriv = 1)$pred_df, "significant")

Advice on a Result

Description

Results of predictmeans functions carry short advice when this fit and these data call for a choice or a caution the user may not know about: an unbalanced design, empty cells, a covariate aliased with a factor, a singular fit, an extrapolated mean, few degrees of freedom, many tests, too few permutations, and so on. Advice is printed at the end of the result as an "Advice:" block (! a caution: the result may mislead as it stands; i a note: a choice worth knowing). It is never generic, and no test is run that was not asked for. advice() returns it as a data frame, for code and AI assistants.

options(predictmeans.advice = FALSE) stops the printing; the advice is still stored.

Usage

advice(x)

Arguments

x

A result of predictmeans(), contrastmeans(), anova() of an lmer or semireg fit, pm_check(), permmodels(), bootmodels(), R2_model(), varcomp(), se_ranef(), semireg(), semipred(), covariatemeans() or pm_slopes().

Value

A data frame with columns id (stable, listed below), level ("caution" or "note") and text; zero rows when there is no advice.

Advice ids

id from when
nonestimable_means predictmeans some means cannot be estimated (NA)
empty_cells predictmeans means average over the observed cells only
aliased_covariate predictmeans a covariate is constant within a factor's levels
large_se predictmeans a mean's SE is over 3 times the median SE
lsd_varies predictmeans the average LSD judges some pair differently from its own test
bias_adjust predictmeans, covariatemeans back-transformed means are a typical cluster's or a median, not the mean
contrast_common_cells contrastmeans contrasts are estimated on the cells their means share
small_df predictmeans, contrastmeans degrees of freedom below 5
many_tests_unadjusted predictmeans, contrastmeans 6 or more requested tests with adj = "none"
singular_fit predictmeans, contrastmeans, R2_model, semireg a variance at zero or a correlation at +-1
anova_unbalanced_typeI, _typeII, _typeIII anova unbalanced data: what the type tests
anova_empty_cells anova empty cells: no type tests a main effect over all cells
anova_covariate_zero anova Type III with a covariate in an interaction (tests at covariate = 0)
check_<name> pm_check a check worth a look (the note of its row)
few_permutations permmodels, bootmodels fewer than 999 resamples and a p-value at the floor or near 0.05
r2_latent_scale R2_model a non-gaussian model: R2 on the link scale
variance_at_zero varcomp, se_ranef a variance estimated as zero
few_re_levels varcomp, se_ranef a random effect with fewer than 5 levels
variance_test_boundary varcomp how to test a variance against zero (test = TRUE)
ranef_conditional_fixed se_ranef conditional SEs of a random term that contains a fixed factor
smooth_linear semireg a smooth estimated as a straight line (variance 0)
extrapolation semipred, covariatemeans, pm_slopes predictions beyond the range of the data
pointwise_regions semipred, covariatemeans regions of difference read from pointwise limits
smooth_other_covariate semipred a smooth in the prediction does not involve covariate (adds a constant)
slopes_equal_by_model pm_slopes no covariate x term interaction: the slopes are equal by assumption
slopes_at_value pm_slopes a curved term or a link: the slopes depend on at

Examples

oats <- nlme::Oats
oats$nitro <- factor(oats$nitro)
fm <- lme4::lmer(log(yield) ~ nitro * Variety + (1 | Block), data = oats)
res <- predictmeans(fm, "nitro:Variety", pairwise = TRUE)
advice(res)

ANOVA Tables for lmer Fits with Kenward-Roger or Satterthwaite df

Description

anova() of a single lmer fit (and of a gaussian semireg fit, fit$semer) gives F tests with denominator degrees of freedom, computed by the package's own code: Type III tests with Kenward-Roger df by default, as SAS PROC MIXED DDFM=KR. This replaces the tables of lmerTest, which predictmeans attached before 2.0. With several models, anova(m1, m2) is lme4's likelihood ratio comparison, unchanged.

Usage

## S3 method for class 'lmerMod'
anova(
  object,
  ...,
  type = c("III", "II", "I"),
  ddf = c("Kenward-Roger", "Satterthwaite", "lme4"),
  advice = TRUE
)

Arguments

object

An lmer fit (class lmerMod).

...

Other fitted models: then lme4's comparison of the models.

type

"III" (default), "II" or "I"; also 3, 2, 1.

ddf

"Kenward-Roger" (default), "Satterthwaite" or "lme4".

advice

Logical: add a note on the choice of type when the data are unbalanced or have empty cells (default TRUE).

Details

Type III hypotheses do not depend on the contrasts the model was fitted with (sum-to-zero coding, as SAS Type 3). With empty cells (aliased coefficients) each term is tested on the cells with data: an interaction by its contrasts that use no empty cell (one df fewer per empty cell), a main effect whose means average over empty cells on the cells its means share, as pm_joint; the table says so, and the intercept is not tested; Type II are those of car::Anova(); Type I (sequential) are lmerTest's, always with Satterthwaite df. Kenward-Roger F tests use the adjusted covariance of the fixed effects (pbkrtest's, observed information); a variance component estimated as zero is left out of the adjustment, as in SAS. ddf = "lme4" gives lme4's own table (sums of squares and F values without df or p-values).

With lmerTest attached, lmer() is lmerTest's and its fits are of class lmerModLmerTest: their anova() and summary() are lmerTest's (Satterthwaite by default), and this method applies to fits of lme4::lmer(). Everything else in predictmeans works the same with either class.

Value

An anova table: for each term the numerator df, the denominator df (column heading names the method), the F value and its p-value. With advice = TRUE a note on the type is kept in attr(, "advice") (read it with advice).

Which type of test

With balanced data (equal numbers in all cells) Types I, II and III give the same tests. With unbalanced data:

Type I

sequential: each term adjusted for the terms before it, so the order in the formula matters. Use it when the order is meaningful, e.g. a block or a covariate to be removed first.

Type II

each term adjusted for all terms that do not contain it (the principle of marginality). The most powerful tests of main effects when the interactions are negligible; with an interaction present the main effects are not well defined.

Type III

each term adjusted for all others, testing equally weighted cell means; meaningful with an interaction present, and here independent of the model's contrasts. A covariate in an interaction makes the other terms be tested at covariate = 0: centre it.

With empty cells no type answers the question of a main effect over all cells: Type III uses the cells with data (and says so). State the comparisons of interest on the cell means instead, with pm_joint or predictmeans.

See Also

anova.semireg, pm_joint, df_term, permmodels

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
anova(fm)
anova(fm, ddf = "Satterthwaite")
anova(fm, type = "I")

Tests for a Semi-Parametric Model

Description

Tests of the fixed effects and of the smooth terms of a semireg or semireg_tmb fit, with the package's own code (no lmerTest needed).

Usage

## S3 method for class 'semireg'
anova(object, type = c("III", "II", "I"), smooth = TRUE, ...)

Arguments

object

A semireg or semireg_tmb fit.

type

"III" (default), "II" or "I" (also 3, 2, 1): the type of the tests of the fixed effects. Type I is sequential (Satterthwaite F for gaussian fits, Wald chi-square otherwise); see anova.lmerMod for which type to use.

smooth

Logical: test the smooth terms (refits the model once per smooth block)? The default is TRUE.

...

Not used.

Details

Fixed effects: Type III (or II) tests from pm_anova(): for gaussian fits Wald F tests with Kenward-Roger df and the adjusted covariance (the df equal those of the same model fitted by nlme::lme); for generalized fits Wald chi-square tests. The fixed parts of the smooths (e.g. x and f:x for s(x, by = f)) are tested here: they are the straight-line parts of the curves.

Smooth terms: for each block of smooth random effects (one variance), the likelihood ratio test of the variance being zero, i.e. of the curve being its straight-line part: the model is refitted without the block (with the same fixed effects, so REML likelihoods can be compared for gaussian fits). The tests are those of varcomp(fit, test = TRUE): as the variance is on the boundary of its range under the null hypothesis, the reference is the mixture \frac12\chi^2_0 + \frac12\chi^2_1 (Self and Liang, 1987), and for the only random effect of a gaussian fit the exact null distribution of the restricted likelihood ratio (Crainiceanu and Ruppert, 2004), where the mixture is conservative; lmerTest::ranova() used the full chi-square, more conservative still. Column test names the distribution. For an s(x, f) smooth the block of the deviation curves tests whether the curves of the levels of f have the same shape. For small samples permlmer or bootmodels on fit$semer give resampling tests.

Value

A list of class "pm_semi_anova" with fixed (the table of the fixed effects) and smooth (a data frame: the variance of each smooth block, the log-likelihoods of the model with and without it, the likelihood ratio statistic, its p-value and the reference distribution), printed together. Advice on the type of tests is kept as for anova.lmerMod (see advice).

References

Crainiceanu, C. M. and Ruppert, D. (2004). Likelihood ratio tests in linear mixed models with one variance component. Journal of the Royal Statistical Society B, 66, 165-185.

Self, S. G. and Liang, K.-Y. (1987). Asymptotic properties of maximum likelihood estimators and likelihood ratio tests under nonstandard conditions. Journal of the American Statistical Association, 82, 605-610.

See Also

anova.lmerMod, varcomp, semipred

Examples

library(predictmeans)
data(Dialyzer, package = "nlme")
fm <- semireg(rate ~ s(pressure, QB, k = 6) + (1 | Subject), data = Dialyzer)
anova(fm)

Plots of Curves, Surfaces and Their Differences

Description

autoplot() draws a result of covariatemeans or semipred as a ggplot2 object (a plotly widget for type = "3d"): the curves with their bands and the data, surfaces as filled contours, slopes (semipred(deriv = )) with the line at zero, or the difference of two curves (contr). It reads the tables of the result only, so the layout can be changed without computing again. plot = TRUE in covariatemeans() and semipred() prints it, and $plt of the result holds it; their plot_args (superseded) give the same arguments under their 1.x names. Those settings are kept in the result (attr(x, "plot_args")) and are the defaults of autoplot(x); arguments given to autoplot() win (autoplot(x, interval = "ci") draws the bands of a result made with ci = FALSE).

The curves and their bands share one legend. When each panel is one group (one factor, the default layout) the strips name the groups and there is no legend. With more than 8 groups the colours are evenly spaced hues, and with more than 12 the legend is set in columns with small keys; panel = character(0) puts all curves in one panel.

Usage

## S3 method for class 'pm_curves'
autoplot(object, type = NULL, group = NULL, panel = NULL,
         scales = c("fixed", "free", "free_x", "free_y"), scale = NULL,
         data = TRUE, jitter = 0, interval = c("ci", "none"), title = NULL,
         style = list(), ...)

Arguments

object

A result of covariatemeans or semipred.

type

"lines" (one covariate: curves or slopes), "surface" (two covariates: filled contours, one panel per level), "3d" (two covariates: a plotly 3-D surface, one widget with a scene per level; needs plotly) or "difference" (a result with contr). The default is "difference" with contr, else "lines" or "surface" by the number of covariates.

group, panel

Names of factors of modelterm: group colours the curves, panel makes the panels (one factor: facet_wrap(); two: facet_grid() rows by columns; more: the first gives the rows, the others together the columns). Factors in neither are joined to group, so each combination has its own curve. The defaults: with one factor, colour and one panel per level (as 1.x); with more, the first factor colours and the others make the panels. panel = character(0) draws one panel. These replace plotord and trellis of 1.x.

scales

The axes of the panels: "fixed" (default), "free", "free_x", "free_y".

scale

"model" (the link or the transformed response, column estimate) or "response" (the back-transformed curves, columns response...). Default: "response" when the curves are back-transformed. For contr: "model" shows the difference (as a ratio or odds ratio for a log or logit), "response" the difference of the back-transformed curves; the default is contr_scale of the call. Slopes are on the model scale.

data

Draw the data (TRUE, jittered by jitter): the original response on the response scale, the modelled one on the model scale (none for a link on the model scale). Not drawn for slopes and differences.

jitter

Jitter of the data points, in x and y (units of the axes).

interval

"ci": the band the result has (simultaneous with band = "simultaneous"); "none".

title

The title; NULL gives the default (covariatemeans(): that of 1.x), FALSE none.

style

Colours and sizes, any of: line and band (one curve), diff_line and diff_band (a difference), ref (the reference line and the marks where a band leaves it out), alpha, linewidth, points, point_alpha, point_size, palette (curves by group; ggplot2's own beyond its length), surface_points.

...

Not used.

Value

A ggplot object, or for type = "3d" a plotly widget. Add to it with ggplot2 (+ labs(y = "Rate")).

See Also

covariatemeans, semipred, tidy.pm_curves

Examples

  library(predictmeans)
  data(Oats, package = "nlme")
  Oats$B <- factor(Oats$Block %in% c("I", "II", "III"), labels = c("late", "early"))
  fm <- lm(yield ~ nitro * Variety * B, data = Oats)
  cm <- covariatemeans(fm, "Variety:B", covariate = "nitro")
  ggplot2::autoplot(cm)                                   # colour Variety, panels B
  ggplot2::autoplot(cm, group = "B", panel = "Variety")
  ggplot2::autoplot(cm, panel = character(0), data = FALSE)

Plots and Summary of Predicted Means

Description

autoplot() draws a predictmeans result as a ggplot2 object: the means with one LSD bar (as predictmeans 1.x), as bars, as horizontal confidence intervals, or the pairwise p-values. plot() draws the same and prints it. summary() prints the means with a footer that states the degrees of freedom, the SED and LSD ranges, the p-value adjustment and the covariate values used. All are built from the means and pairs tables of the result: they do not compute statistics, so they can be used in reports and Shiny apps (e.g. renderPlot(autoplot(pm))) or made interactive with plotly::ggplotly(). Titles, labels and font sizes are changed with ggplot2, e.g. autoplot(pm) + labs(title = "Yield") + theme_bw(14).

Usage

## S3 method for class 'predictmeans'
autoplot(object, type = c("means", "bar", "ci", "pvalue"),
         interval = c("lsd", "sed", "ci", "comparison", "none"),
         scale = c("auto", "model", "response"),
         data = FALSE, x = NULL, group = NULL, panel = NULL,
         scales = c("fixed", "free_y"), lines = TRUE,
         jitter = 0.1, values = FALSE, ...)

## S3 method for class 'predictmeans'
plot(x, ...)

## S3 method for class 'predictmeans'
summary(object, digits = 4, ...)

## S3 method for class 'summary.predictmeans'
print(x, ...)

Arguments

object

A result of predictmeans.

type

"means" (the default): points joined by lines for each level of group; "bar": a bar chart of the means; "ci": each mean with its confidence limits, drawn horizontally (one row per mean; on the response scale when the means are back-transformed); "pvalue": a square level plot of the adjusted pairwise p-values (the plot of PMplot; with atvar the comparisons within each of its levels are blocks down the diagonal), which needs the pairs table. ("response" of earlier 2.0 versions is type = "ci" or scale = "response".)

interval

For "means" and "bar": "lsd" (the default) draws one bar of the average LSD beside the means of each panel, as predictmeans 1.x: two means differ at the level of the result when they are further apart than the bar (exactly so when all the LSDs are equal; the caption gives their range when they are not). It is the LSD that goes with the p-values: adjusted when adj has a critical value. With atvar each panel (level of atvar) gets the LSD of the pairs compared within it. "sed" draws the average SED instead; "ci" confidence limits on each mean (for each mean, not for comparing means: two means can differ while their limits overlap); "comparison" comparison intervals (mean \pm c\,SE, c = crit \times SED/(SE_1 + SE_2) averaged over the pairs: means differ when their bars do not overlap; see predictmeans); "none". One LSD bar replaces the half-LSD bars on each mean of earlier 2.0 versions: those said the same when the SEDs are equal, and looked like confidence limits.

scale

"model": the scale of the model (e.g. log(y + 1) or the link); "response": the back-transformed means (needs them); "auto" (the default): "response" for type = "ci" when the means are back-transformed, else "model". LSD and SED bars exist only on the model scale.

scales

For "means" and "bar" with panels: "fixed" (the default), one y axis for all panels, with the LSD (SED) bar at the same place in each, from the lowest point of the plot, so equal LSDs look equal; "free_y", each panel its own y range, with its bar from its own lowest point (the bars are then read within their panel only: the caption says so).

data

Add the observations (TRUE; jittered points), from pm_data of the model, on the scale shown: the transformed response on the model scale, the original response on the response scale. For a link function the data are shown only on the response scale. A data frame can be given instead (with the factors of modelterm and the response).

x, group, panel

Names of factors of modelterm for the x axis, the lines (colours) and the panels. The defaults: with atvar, the panels are its levels and x the first other factor; else x is the first factor, group the second and the panels the rest. These replace plotord of predictmeans 1.x.

lines

For type = "means": join the means of a group by lines (TRUE) or not.

jitter

Horizontal jitter of the data points, in units of the x categories.

values

For type = "pvalue": print each p-value on its tile (the default is FALSE).

digits

Number of significant digits printed (plus two).

...

For plot(): arguments of autoplot(), with xvar for its x (in plot() x is the result). Otherwise not used.

Value

autoplot() returns a ggplot object; plot() prints it and returns it invisibly; summary() returns an object whose print method shows the table and footer.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

predictmeans, tidy.predictmeans, pm_data, advice

Examples

  library(predictmeans)
  Oats <- as.data.frame(nlme::Oats)
  Oats$nitro <- factor(Oats$nitro)
  fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
  pm <- predictmeans(fm, "nitro:Variety", atvar = "Variety", adj = "tukey")
  summary(pm)
  ggplot2::autoplot(pm)
  ggplot2::autoplot(pm, data = TRUE)
  ggplot2::autoplot(pm, type = "bar")
  ggplot2::autoplot(pm, type = "ci")
  ggplot2::autoplot(pm, type = "pvalue")
  plot(predictmeans(fm, "nitro:Variety"), xvar = "Variety", group = "nitro")
  fl <- lm(log(yield) ~ nitro * Variety, data = Oats)
  ggplot2::autoplot(predictmeans(fl, "nitro:Variety"), type = "ci", data = TRUE)

Parametric Bootstrap Tests

Description

Parametric bootstrap p-values for the terms and coefficients of a model. Responses are simulated from the model fitted without its fixed effects (only an intercept, any offset, and the same random effects and covariance structure: the global null hypothesis), the full model is refitted to each, and a p-value is (b + 1)/(B + 1), b of the B simulated statistics being at least as large as the observed one. Results are the same for any ncore. Useful for GLMs and GLMMs and small samples, where Wald or F tests can be poor.

Usage

bootmodels(model, nsim = 999, type = c("I", "II", "III", "1", "2", "3"), seed = NULL,
           ncore = 1, ...)

Arguments

model

A model fitted by lm, aov (without Error()), glm (a family with a distribution: gaussian, binomial, Poisson, Gamma; also MASS::glm.nb), gls, lme, lmer, glmer or glmmTMB. Responses of lme and gls models are simulated from the null model's covariance of the data (random effects, correlation and variance structures).

nsim

Number of simulated data sets, the default is 999.

type

The type of ANOVA table (as in permmodels): Type I gives sequential F statistics (for a glm with a known dispersion, the deviance; glmmTMB has none and uses Type II), Types II and III Wald chi-square statistics (lm: F; glm: likelihood ratio).

seed

Optional random number seed, for reproducible results; the user's random number stream is left as it was.

ncore

Number of cores for refitting, the default is 1.

...

Not used: prt (before 2.0) stops with its 2.0 spelling; print() of the result shows the tables.

Details

The result has the same form as that of permmodels: its permlist can be given to predictmeans or contrastmeans (argument permlist) for bootstrap p-values of pairwise comparisons or contrasts (p.method "bootstrap" in the pairs table).

In a simulation study (500 data sets per case, 5% level; dev/sim-boot.R in the package sources) the bootstrap corrected the liberal Wald chi-square test of a whole-plot factor in a split plot with 6 blocks (10% to 6-7%, as Kenward-Roger) and kept the level in Poisson and binomial GLMMs, also when other terms had effects. Like the likelihood-ratio test it relies on the model: with overdispersed counts fitted as Poisson it rejected 37% of true null hypotheses, where permmodels (Freedman-Lane on the working scale) gave 7%.

Value

Invisibly, a list with permlist (the coefficients and covariance matrices of the refits), COEFFICENTS and ANOVA (the model's tables with a Boot_p_value column). Attribute "resampling" is "parametric bootstrap"; advice (e.g. on too few samples) in attr(, "advice") (advice).

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

permmodels, varcomp (test_method = "bootstrap"), advice

Examples

  library(predictmeans)
  Oats$nitro <- factor(Oats$nitro)
  fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
  
  bt <- bootmodels(fm, nsim = 99, seed = 1)   # use 999 or more in practice
  predictmeans(fm, "nitro", permlist = bt)$pairs
  

Families of Contrasts among Means

Description

Build a standard family of contrasts among the means of a model term, as a matrix for the ctrmatrix argument of contrastmeans. The families are those of emmeans, with the same coefficients and names:

"pairwise", "revpairwise"

all pairs, earlier minus later level (or later minus earlier);

"trt.vs.ctrl"

each level minus the reference level ref (Dunnett's comparisons; use adj = "mvt" in contrastmeans for the exact Dunnett adjustment);

"consec"

each level minus the one before;

"poly"

orthogonal polynomials (linear, quadratic, ...) with integer coefficients, for equally spaced levels;

"eff"

each level minus the average of all levels;

"del.eff"

each level minus the average of the other levels.

With by, the family is built within each level (or combination of levels) of the by factor(s), as atvar does for pairwise comparisons. Note that contrastmeans adjusts the p-values of all rows as one family.

Usage

contrast_family(.x, family = c("pairwise", "revpairwise", "trt.vs.ctrl", "consec", "poly",
                "eff", "del.eff"), ref = 1, by = NULL, max_degree = NULL, ...)

Arguments

.x

A Kmatrix or predictmeans result for the model term, or a character vector of the level names (then by can't be used).

family

The family of contrasts (see Description).

ref

For "trt.vs.ctrl": the reference level, by position or name (within each by group), the default is the first level.

by

Optional name(s) of factor(s) of the term: build the family within each of their levels.

max_degree

For "poly": the highest degree, the default is the number of levels - 1 (at most 6).

...

Not used: max.degree (before 2.0) stops with its 2.0 spelling.

Value

A matrix with one row per contrast (named as in emmeans, e.g. "0.2 - 0", "linear"; with by the group comes first, e.g. "Victory: 0.2 - 0") and one column per level of the term. Levels whose means can't be estimated are left out of the families.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

contrastmeans, specify_contrast, pm_joint

Examples

  library(predictmeans)
  Oats$nitro <- factor(Oats$nitro)
  fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
  # Dunnett: each nitrogen level against no nitrogen, exact adjustment
  K <- Kmatrix(fm, "nitro")
  if (requireNamespace("mvtnorm", quietly = TRUE)) {
    contrastmeans(fm, "nitro", ctrmatrix = contrast_family(K, "trt.vs.ctrl"),
                  adj = "mvt")
  }
  # linear and quadratic trends in nitrogen within each variety
  K2 <- Kmatrix(fm, "nitro:Variety")
  cf <- contrast_family(K2, "poly", by = "Variety", max_degree = 2)
  contrastmeans(fm, "nitro:Variety", ctrmatrix = cf)

Linear Contrast Tests for a Linear Model

Description

t tests (or permutation t tests) of given contrasts among the predicted means of a model term, for the models of predictmeans (aov, lm, glm, gls, lme, lmer, glmer, glmmTMB, gam).

Usage

contrastmeans(model, modelterm, ctrmatrix, ctrnames=NULL, adj="none", permlist,
              vcov_adjust=TRUE,
              weights=c("equal", "proportional", "outer", "cells", "flat"),
              df_method=c("auto", "Kenward-Roger", "Satterthwaite", "containment",
      "between-within", "KR-expected", "KR-average", "inner-outer", "residual"),
              joint=FALSE, conf_level=0.95, vcov=NULL, equivalence=NULL, ...)

Arguments

model

A fitted model, as for predictmeans.

modelterm

Name (in "quotes") for indicating which factor term's contrast to be calculated. The modelterm must be given exactly as it appears in the printed model, e.g. "A" or "A:B".

ctrmatrix

A specified contrast matrix. If it is missing, an edit window asks for it (interactive sessions only). The columns can be named by level (e.g. from specify_contrast); levels that are not given get zero weight.

ctrnames

Names of the specified contrasts, e.g. c("A vs D", "C vs B", ...)

adj

Name (in "quote") for indicating a method for adjusting p-values of pairwise comparisons. The choices are "none", "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "sidak", "scheffe", "mvt" and "westfall", in any letter case. "sidak", "scheffe" (rank of ctrmatrix) and "mvt" (single-step multivariate t, the exact counterpart of SAS ADJUST=SIMULATE; needs package mvtnorm) are as in emmeans. With permlist, "mvt" gives the single-step and "westfall" the step-down max-|t| adjustment of the permutation p-values (Westfall and Young, 1993); "westfall" needs permlist, and "scheffe" is not available with it. The default method is "none".

permlist

A list from permmodels: each contrast is then tested by permutation, with p-value (b + 1)/(B + 1) (b of the B permuted |t| at least the observed one), and df_method is not used. With the result of permmodels(method = "freedman-lane") (lm and aov models), each contrast is tested by Freedman-Lane permutations of the model in which that contrast is 0. With a permlist, vcov_adjust is not used (the permuted refits use the unadjusted covariance).

vcov_adjust

For models fitted by REML (lmer, lme, gls) with Kenward-Roger df: if TRUE (the default), standard errors use the Kenward-Roger adjusted covariance matrix of the fixed effects, as SAS DDFM=KR and emmeans do, to go with the Kenward-Roger degrees of freedom. FALSE uses the unadjusted covariance and reproduces results of predictmeans 1.x. It has no effect for other models.

weights

Passed to Kmatrix: how the cells of factors not in modelterm are weighted when averaging over them ("equal", the default, "proportional", "outer", "cells" or "flat").

df_method

Denominator df, by method or as one number (a fixed df, Df before 2.0): "auto" (Kenward-Roger for REML fits of lmer, lme and gls, Satterthwaite for ML fits), "Kenward-Roger", "Satterthwaite" or "containment" (SAS DDFM=CONTAIN), and for lmer, lme and gls models "between-within" (SAS DDFM=BETWITHIN), and "KR-expected" (Kenward-Roger with the expected information, as pbkrtest; "Kenward-Roger" uses the observed information, as SAS DDFM=KR), "KR-average" (the average information, as Genstat); for lme and gls also "Satterthwaite", "Kenward-Roger", "KR-expected", "KR-average" and "containment" (nlme's or the residual df, as predictmeans 1.x); see predictmeans.

joint

Logical: also test all the contrasts together (all of them zero), as pm_joint does: an F test with Kenward-Roger (REML fits, the scaled F of Kenward and Roger, 1997) or Satterthwaite (ML fits) denominator df, the residual df for other models (normal-based, i.e. chi-square / df1, when there is none). Contrasts that are linear combinations of others are dropped, so df1 is the rank of ctrmatrix. With permlist, also a permutation p-value of the joint Wald F statistic, from the same permutations (for Freedman-Lane, the model with all the contrasts zero). The default is FALSE.

conf_level

Confidence level of the limits of the contrasts (level = 0.05 before 2.0); the tests are at the significance level 1 - conf_level. The limits are t limits of each contrast, or with permlist permutation-t limits: estimate +- c SE, with c the critical value of the permutation test (the k-th largest permuted |t|, k = floor((1 - conf_level) (nperm + 1))). With adj "bonferroni", "sidak", "scheffe" or "mvt" (with permlist: "bonferroni", "sidak", "mvt" or "westfall", from the largest permuted |t| of the contrasts) the table also has adj.lower.CL and adj.upper.CL: simultaneous limits that exclude 0 exactly when the adjusted p-value is below 1 - conf_level, as emmeans' confint() and SAS AdjLower/AdjUpper. The step-down and false discovery rate methods have none.

vcov

Optional covariance of the coefficients to use instead of the model's. For lm, aov and glm models: "HC0", "HC1", "HC2" or "HC3" (heteroscedasticity-consistent, as sandwich::vcovHC()), or a one-sided formula naming a cluster variable of the data, e.g. ~ Block (cluster-robust CR1, as sandwich::vcovCL()). For any model: a covariance matrix of the coefficients, or a function that returns one from the model (for mixed models e.g. from the clubSandwich package). The degrees of freedom stay those of the model (the residual df; for lmer Kenward-Roger or Satterthwaite df computed from the model), and vcov_adjust is not used. With a permlist, vcov is not used (for robust permutation tests see permmodels(robust = TRUE)). The default NULL uses the model's covariance.

equivalence

Optional equivalence margins for equivalence tests (two one-sided t tests, TOST) of the contrasts: a positive number d (equivalence region -d to d) or c(lower, upper), on the scale of the comparisons (the link scale for GLMs: e.g. log ratios). The TOST p-value is the larger of the two one-sided p-values; below 1 - conf_level, the difference lies within the margins (as emmeans' test(..., side = "equivalence")). Not adjusted for multiplicity; with a permlist it is t-based (normal-based in contrastmeans).

...

Not used: arguments removed in 2.0 (Df, level) stop with their 2.0 spelling.

Value

An object of class "contrastmeans", a list. print() shows the contrasts, tidy() and as.data.frame() return the table contrasts (what = "joint": the joint test). Its first components are those of 1.x:

The t tests of the specified contrasts

A table (rounded to 4 decimals) of the t tests of the contrasts, with the adjusted p-value in Pr(>|t|).

K

A contrast matrix.

Joint F test of the contrasts

With joint = TRUE: df1, df2, F.ratio and p.value of the joint test (and Perm_p_value with permlist).

and then the tables in the layout of predictmeans, unrounded:

contrasts

One row per contrast: contrast (its name), over (contrasts of means over empty cells: the cells used), estimate, std.error, df, statistic (t), p.value (unadjusted; with permlist the permutation p-value), p.adj (adjusted by adj), p.equiv (with equivalence), conf.low, conf.high, adj.conf.low, adj.conf.high (simultaneous, with the adjustments that have them), p.method, and for a log or logit scale (link, or a log response) ratio or odds.ratio with its limits when the weights of every contrast sum to zero.

joint

With joint = TRUE: the joint test, unrounded.

settings

modelterm, level (significance level, 1 - conf_level), adjust, df_method, vcov_adjust, vcov, equivalence, nperm, model_class, version.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Torsten Hothorn, Frank Bretz and Peter Westfall (2008), Simultaneous Inference in General Parametric Models. Biometrical, Journal 50(3), 346–363.

See Also

specify_contrast, contrast_family, pm_joint, predictmeans, tidy.predictmeans, advice

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)

# 1. Enter a contrast matrix in an edit window (interactive sessions only)
if (interactive()) contrastmeans(fm, "nitro:Variety")
 
# 2. Give the contrast matrix: Victory - Golden Rain at nitro 0, Victory at 0 - Marvellous at 0.4
cm <- rbind(c(-1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), 
            c(0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0))
contrastmeans(fm, "nitro:Variety", ctrmatrix=cm)

# 3. ... and both contrasts tested together (an F test with 2 numerator df)
ct <- contrastmeans(fm, "nitro:Variety", ctrmatrix=cm, joint=TRUE)
ct
as.data.frame(ct)

Copper Grade at Sampling Points

Description

Copper grade at sampling points with their X, Y and Z coordinates within a designated area. Used in the overview article to fit a semiparametric model with a smooth in Z and a thin-plate spline in X and Y.

Usage

data(copper)
data(copperKnots)

Format

A data frame with 439 rows and 4 columns:

xcoord

X coordinate of the sampling point.

ycoord

Y coordinate of the sampling point.

zcoord

Z coordinate of the sampling point.

grade

copper grade (positive; modelled on the log scale below).

copperKnots: the 20 knots (columns xcoord, ycoord) of M. P. Wand's thin-plate spline fit of these data (a geoadditive model fitted by lme()), which semireg reproduces.

Examples

data(copper)
data(copperKnots)
# M. P. Wand's geoadditive model: a thin-plate surface over the plane with the given knots,
# and an O'Sullivan spline in depth (their linear terms are added to the fixed effects)
mod <- semireg(grade ~ s(xcoord, ycoord, bs = "ztps", xt = list(knots = as.matrix(copperKnots))) +
                 s(zcoord, bs = "os", xt = list(knots = seq(80, 120, by = 5))), data = copper)
anova(mod)   # fixed effects (Kenward-Roger) and a test of each smooth term
semipred(mod, covariate = c("xcoord", "ycoord"))$plt

# on the log scale, with the pairwise interactions of the coordinates
mod2 <- semireg(log(grade) ~ s(zcoord, bs = "os") + s(xcoord, ycoord, bs = "ztps", k = 6) +
                  xcoord:ycoord + xcoord:zcoord + ycoord:zcoord, data = copper)
semipred(mod2, covariate = "zcoord", trans = exp)$plt


Predicted Means of a Linear Model with Covariate Variable(s)

Description

Predicted means along a covariate for each level of a factor term (curves) with their confidence limits, or the difference between two of the curves with its band. The result holds the tables in the layout of predictmeans and the plot, which autoplot() returns.

Usage

covariatemeans(model, modelterm=NULL, covariate, as_is=FALSE, at=NULL, data=NULL,
  conf_level=0.95, trans=NULL, cov_reduce=mean, exclude=NULL,
  weights=c("equal", "proportional", "outer", "cells", "flat"),
  df_method=c("auto", "Kenward-Roger", "Satterthwaite", "containment",
    "between-within", "KR-expected", "KR-average", "inner-outer", "residual"),
  vcov_adjust=TRUE, contr=NULL, contr_scale=c("model", "response"),
  band=c("pointwise", "simultaneous"), bias_adjust=FALSE, sigma=NULL,
  mean_type=c("conditional", "overall"), plot=getOption("predictmeans.plot", FALSE),
  plot_args=list(), ...)

Arguments

model

A fitted model, as for predictmeans (aov, lm, glm, gls, lme, lmer, glmer, glmmTMB, gam).

modelterm

Name (in "quotes") of the factor term whose lines are predicted, e.g. "A" or "A:B", given exactly as it appears in the printed model.

covariate

Name (in "quotes") of a covariate of model, or two names for surfaces (then at is a matrix with a column per covariate, or NULL for a grid; not with contr or as_is).

as_is

TRUE: each line only over the range of the covariate observed in its group (rows outside it are left out of the result); the default FALSE uses the values of at for every group.

at

The values of covariate at which the lines are predicted (covariateV before 2.0); by default 50 values over the observed range. See Kmatrix.

data

The data used to fit the model; needed in some cases, e.g. when a variable is transformed in the model formula.

conf_level

The confidence level of the limits, the default is 0.95 (level = 0.05 before 2.0). The limits are for each line on its own: whether the bands of two groups overlap is not a test of their difference (the lines are estimated from the same model and are correlated; see letter_ci in predictmeans). Use contr for the band of the difference between two groups, or compare groups at chosen covariate values with predictmeans (covariate = ) and their slopes with pm_slopes.

trans

A function object for calculating the back transformed means, e.g. trans=exp. When it is not given, the inverse link of the model is used, or the inverse of a transformation of the response in the model formula (log(y), sqrt(y), ...; see predictmeans), with a message; trans = I keeps the model scale. The back-transformed line is the back-transformed fitted value. (Before 2.0 half the standard error of the fitted value was added inside exp() for a log.)

plot_args

Superseded by the arguments of autoplot.pm_curves, kept for 1.x scripts: a named list (names may be abbreviated) of trellis (FALSE: one panel; panel = character(0)), plotord (the order of the factors, e.g. c(2, 1) or c("B", "A"): the first colours the lines, the others make the panels; group, panel; giving it draws the plot), mtitle (title), ci (interval), point (data), jitterv (jitter), scales and the colours of style. Before 2.0 these were arguments of their own; given so they stop with this spelling.

...

Not used: arguments removed in 2.0 (level, Df, covariateV, transOff, responsen, newwd, the plot settings) stop with their 2.0 spelling (see vignette("migrating")).

cov_reduce

How covariates that are not varied are handled when building the predicted means: a function such as mean (the default) or median, or "average" to average the predictions over the observed covariate values (e.g. means adjusted for a spatial smooth in a gam). See Kmatrix.

exclude

For gam models: smooth terms to leave out of the predictions. The default excludes random-effect smooths. See Kmatrix.

weights

Passed to Kmatrix: how the cells of the factors that are not in modelterm are weighted when averaging over them: "equal" (the default; equal weights), "proportional" (weights proportional to the frequencies of those cells in the data, the same for every mean, as SAS LSMEANS / OM), "outer" (products of each factor's own frequencies), "cells" (each mean weights the cells by their own frequencies) or "flat" (equal weights over the non-empty cells). The definitions are those of emmeans.

df_method, vcov_adjust

As in predictmeans (a number in df_method is a fixed df, Df before 2.0): by default Kenward-Roger df (each point of the curves has its own) and adjusted standard errors for models fitted by REML (lmer, lme, gls). predictmeans 1.x used the unadjusted covariance and, for lmer, one df per term; vcov_adjust = FALSE and, for lme and gls, df_method = "containment" give its results.

contr

Two levels of modelterm, by their names as in the data (e.g. c("Golden Rain", "Victory")) or by their numbers (c(1, 3); for a term with several factors the combined labels such as "a:x"): the difference between the first and the second along the covariate, with its confidence band, is returned and plotted instead of the lines. See ‘Comparing two lines’.

contr_scale

With contr: what is plotted. "model" (the default) is the difference on the scale of the model, where the test is made; for a log link or a log response it is shown as the ratio of the two lines and for a logit link as the odds ratio (exact: exp of the difference and of its limits). "response" is the difference of the back-transformed lines, in the units of the response, with a delta-method band; it describes the size of the difference, the test stays on the model scale.

band

With contr: "pointwise" (the default) gives limits at the confidence level conf_level for each covariate value on its own; "simultaneous" gives Scheffe limits that hold for all covariate values together, for saying over which range of the covariate the lines differ.

mean_type

Only for glmmTMB fits with zero inflation (ziformula; ignored, with a message, for other models): "conditional" (default), curves of the means of the count part, \mu; "overall", curves of the overall means (1 - \pi)\mu (\pi the probability of an extra zero), their bands \exp(\log m \mp crit\,SE) with the SE of \log m from the joint covariance of the count and zero-inflation coefficients (delta method), and with contr the ratio and the difference of the overall means. Log-link count families only.

plot

Draw the plot now? The default is FALSE (since 2.0; 1.x drew it): autoplot() of the result draws it (autoplot.pm_curves: layouts, scales, data), and $plt holds the default plot. plot = TRUE, or options(predictmeans.plot = TRUE) for a whole session, draws it as 1.x did; plot_args = list(plotord = ) also draws it.

bias_adjust, sigma

For back-transformed lines (a link, a transformed response or trans), as in predictmeans. By default a line is the back-transformed fitted value: the median of the response for a transformed response (the geometric mean for a log), and the response of a typical cluster (random effects at zero) for a generalized linear mixed model. bias_adjust = TRUE gives the mean of the response instead (for a mixed model: averaged over the clusters), computed over the variation on the model scale: the residual variance for a transformed response plus the variances of the random intercepts, or sigma^2 when sigma is given (needed with random slopes). It is exact (for a log the factor exp(\sigma^2/2), for a square root + \sigma^2); "taylor" is the second-order formula of emmeans. Use it for totals and expected amounts; ratios and tests do not need it. The limits treat the variance as known. With contr the response-scale difference is that of the adjusted lines.

Value

An object of class c("covariatemeans", "pm_curves"), a list. Its tables have the layout of predictmeans (columns estimate, std.error, df, conf.low, conf.high, ..., the covariate under its own name; see tidy.pm_curves); tidy() and as.data.frame() return them, autoplot() the plot, and print() shows a summary.

means

The curves: one row per level of modelterm and covariate value (NULL with contr).

pairs

With contr: the difference of the two curves at each covariate value.

settings

The options that produced them (df method, level, band, back-transformation, ...).

plt

autoplot() of the result with plot_args (a ggplot); drawn only with plot = TRUE.

pred_df

(pltdf before 2.0; x$pltdf still gives it, with a message once per session) The 1.x table: the fitted values with their limits, or with contr the differences on the model scale and, when there is a back-transformation, on the response scale.

test, significant

With contr: the joint F test that the two lines are the same (numerator and denominator df, F, p-value), and the ranges of the covariate where the band leaves out zero.

Comparing two lines

Whether the bands of two lines overlap does not say whether the lines differ: the lines are estimated from the same model and are correlated. The band of their difference does, and it is computed from the contrast of the two lines, not from their limits.

The scale of the test. The difference is tested on the scale of the model (the link, or the transformed response): there the model is additive, the estimates are closest to normal and the standard error does not depend on the mean. d = (K_a - K_b)\hat\beta, SE^2 = (K_a - K_b) V (K_a - K_b)', limits d \pm c\,SE (columns diff, ses, Df, LL, UL). With a log the difference back-transforms exactly to a ratio and with a logit to an odds ratio (columns ratio or odds.ratio with their limits): the limits leave out 1 exactly when those of diff leave out 0, so nothing is approximated. For other transformations (square root, probit, a power) the back-transformed difference has no meaning and the model scale is shown.

Why back-transform. Only to read the size of the difference in the units of the response; it is not needed to decide whether the lines differ. The response-scale difference h(\eta_a) - h(\eta_b) is another quantity: its standard error is an approximation (the delta method, gradient h'(\eta_a) K_a - h'(\eta_b) K_b; columns response.diff, response.ses, response.LL, response.UL), it depends on the values of the other variables of the model, and lines that are parallel on the model scale are not parallel on the response scale. Its band can disagree with the test near the boundary, so with contr_scale = "response" the covariate values where the lines differ are still those of the model scale (marked along the axis). For a generalized linear mixed model it is the difference for a typical cluster (random effects at zero), as the lines are.

Significance at a level. Three questions have three answers:

  1. At one covariate value chosen beforehand: the pointwise band (band = "pointwise"); the lines differ at the level 1 - conf_level when it leaves out zero (one for a ratio).

  2. Over which range of the covariate: looking at many values needs wider limits. band = "simultaneous" uses Scheffe's critical value c = \sqrt{r F_{1-\alpha;\,r,\,df}}, r the rank of the contrasts along the covariate (2 for straight lines: the Working-Hotelling band). It holds for every covariate value at once and is slightly conservative over a limited range.

  3. Whether the lines differ anywhere: the joint F test that all the differences along the covariate are zero (test in the result).

Each set of limits in pred_df has a column that says whether it includes the value of no difference: includes0 for diff, ratio.includes1 or odds.ratio.includes1 (always equal to includes0) and response.includes0 for the response-scale difference (which can differ from includes0 near the boundary). Column significant (!includes0) and significant in the result (the ranges of the covariate) follow the band asked for, on the model scale.

Zero inflation (glmmTMB)

For a glmmTMB fit with zero inflation (ziformula) the means are those of the conditional (count) part, \mu, as emmeans and predict(type = "conditional") give, not the overall mean (1 - \pi)\mu (\pi the probability of an extra zero); ratios are of these means, and equal the ratios of overall means only when \pi is the same. A message says so and settings$component is "conditional". The two can order treatments differently when \pi differs between them. mean_type = "overall" (predictmeans(), covariatemeans(), semipred()) gives the overall means and their ratios.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

autoplot.pm_curves, tidy.pm_curves, advice, pm_slopes, predictmeans

Examples

  library(predictmeans)
  data(Oats, package="nlme")
  fm <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)
  cm <- covariatemeans(fm, "Variety", covariate="nitro")
  ggplot2::autoplot(cm)
  ggplot2::autoplot(cm, panel = character(0), data = FALSE)   # one panel, no data
  covariatemeans(fm, "Variety", covariate="nitro", at=seq(0, 0.6, 0.3))
# the difference between two varieties along nitro, with a simultaneous band
# (the two levels by name, or by number: contr=c(1, 3))
  cd <- covariatemeans(fm, "Variety", covariate="nitro", contr=c("Golden Rain", "Victory"),
                       band="simultaneous")
  cd$settings$test
  head(as.data.frame(cd))

Denominator Degrees of Freedom of the Means or Contrasts of an lmer Model

Description

The denominator df of each mean of a model term, or of each row of a contrast matrix, for an lmer fit: Kenward-Roger (default), Satterthwaite, containment or between-within.

Usage

df_term(model, modelterm, covariate=NULL, ctrmatrix=NULL, ctrnames=NULL,
        df_method=c("Kenward-Roger", "Satterthwaite", "containment",
          "between-within", "KR-expected", "KR-average"), ...)

Arguments

model

Model object returned by lmer.

modelterm

Name (in "quotes") of the model term whose means get df, as written in the model formula, e.g. "A" or "A:B".

covariate

Name (in "quotes") of a covariate in the model, passed to Kmatrix.

ctrmatrix

A contrast matrix on the fixed-effect coefficients (one column per coefficient of fixef(model)). When given, modelterm is ignored (except for "containment" and "between-within", which need it).

ctrnames

Names of the rows of ctrmatrix, e.g. c("A vs D", "C vs B").

df_method

The method for the degrees of freedom (called type before 2.0): "Kenward-Roger" (the default), "Satterthwaite", "containment", "between-within", "KR-expected" or "KR-average". Kenward-Roger needs a REML fit; for models fitted by ML, Satterthwaite is used with a warning. "containment" gives the SAS DDFM=CONTAIN df of modelterm (needed then) for every row, and "between-within" the SAS DDFM=BETWITHIN df (see predictmeans). "Kenward-Roger" uses the observed information of the variance parameters, as SAS DDFM=KR; "KR-expected" the expected information, as pbkrtest and emmeans; "KR-average" the average information, as Genstat.

...

Arguments removed in 2.0 (type, vcov_adj) stop with their 2.0 spelling.

Details

Kenward-Roger df that cannot be computed fall back to Satterthwaite with a warning. The Satterthwaite df equal those of lmerTest and the Kenward-Roger df those of pbkrtest ("KR-expected") and SAS DDFM=KR (‘tests/testthat/test-satterthwaite.R’, ‘test-kr-sas.R’).

Value

A numeric vector of df, one per mean of modelterm (rows of Kmatrix(model, modelterm)$K) or per row of ctrmatrix.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

predictmeans (argument df_method), anova.lmerMod, contrastmeans

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lmer(yield ~ nitro*Variety+(1|Block/Variety), data=Oats)
df_term(fm, "nitro:Variety")
df_term(fm, "nitro:Variety", df_method = "containment")
# two contrasts of the 12 coefficients
cm <- rbind(c(-1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0),
            c(0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0))
df_term(fm, ctrmatrix=cm, df_method="Satterthwaite")

Growth of Indiana Children

Description

Repeated height measurements of 216 adolescents, about every 6 months between the ages of 5 and 20, from a study of the development of hypertension at the Indiana University School of Medicine, Indianapolis (Pratt et al. 1989); the same data as HRW::growthIndiana. The data of M. P. Wand's examples of subject-specific curves (Harezlak, Ruppert and Wand 2018, section 9.2), which semireg reproduces (tests/testthat/test-semireg-golden.R).

Usage

data(growthIndiana)

Format

A data frame with 4123 rows and 5 columns:

idnum

identification number of the adolescent.

height

height (cm).

age

age (years).

male

1 for a boy, 0 for a girl.

black

1 for a black adolescent, 0 otherwise.

Source

Pratt, J. H., Jones, J. J., Miller, J. Z., Wagner, M. A. and Fineberg, N. S. (1989). Racial differences in aldosterone excretion and plasma aldosterone concentrations in children. New England Journal of Medicine, 321, 1152-1157.

References

Harezlak, J., Ruppert, D. and Wand, M. P. (2018). Semiparametric Regression with R. Springer.

Examples

data(growthIndiana)
# black boys: a mean curve, and each boy's own curve, a straight line (age | idnum)
# plus a spline deviation with one variance for all boys
gbm <- subset(growthIndiana, male == 1 & black == 1)
gbm$idnum <- factor(gbm$idnum)
fit <- semireg(height ~ s(age, bs = "os", k = 20, xt = list(range = c(5.5, 20))) +
                 (s(age, k = 10, xt = list(range = c(5.5, 20))) | idnum), data = gbm)
anova(fit)$smooth       # are the boys' curves straight lines?
semipred(fit, "age", "age")$plt
## Not run: 
# (about 30 s: 2257 measurements, 130 boys' curves)
# all boys: a common curve and a black-white deviation curve (the contrast curve of
# Harezlak, Ruppert and Wand); at which ages do the races differ, and in growth rate?
gm <- subset(growthIndiana, male == 1)
gm$idnum <- factor(gm$idnum)
gm$race <- factor(ifelse(gm$black == 1, "black", "white"))
fit2 <- semireg(height ~ s(age, race, bs = "os", k = 20, xt = list(range = c(5.5, 20))) +
                  (s(age, k = 10, xt = list(range = c(5.5, 20))) | idnum), data = gm)
dif <- semipred(fit2, "race", "age", contr = c("black", "white"), band = "simultaneous")
attr(dif$pred_df, "significant")
semipred(fit2, "race", "age", deriv = 1)$plt     # growth rates
predictmeans(fit2, "race", covariate = c(age = 12))$means

## End(Not run)

Ozone Concentration and Meteorology in California

Description

Daily ozone concentration with three meteorological variables (345 days), a version of the Los Angeles ozone data of Breiman and Friedman (1985); the data of M. P. Wand's additive model examples (fitted by lme() and by gam()).

Usage

data(ozoneCalif)

Format

A data frame with 345 rows and 4 columns:

ozone

ozone concentration.

inversion.base.height

inversion base height.

daggett.pressure.gradient

pressure gradient (Los Angeles to Daggett).

inversion.base.temp

inversion base temperature.

Source

Breiman, L. and Friedman, J. H. (1985). Estimating optimal transformations for multiple regression and correlation. Journal of the American Statistical Association, 80, 580-598.

Examples

data(ozoneCalif)
# an additive model: three O'Sullivan splines
fit <- semireg(ozone ~ s(inversion.base.height, bs = "os", k = 15) +
                 s(daggett.pressure.gradient, bs = "os", k = 15) +
                 s(inversion.base.temp, bs = "os", k = 15), data = ozoneCalif)
anova(fit)$smooth     # is each curve more than a straight line?
# the effect of one covariate, the others at their means
semipred(fit, covariate = "inversion.base.temp")$plt

Combine Permutation Tests of Several Responses

Description

Nonparametric combination (NPC) of permutation tests made with the same permutations, for example the same model fitted to several responses (traits, time points) measured on the same units: for each term or coefficient, one p-value for the hypothesis that it has no effect on any of the responses, and p-values adjusted for testing it on every response.

Usage

permcombine(..., method = c("fisher", "tippett"), tests = NULL)

Arguments

...

Results of permmodels with Freedman-Lane permutations (the default), all made with the same permutations: the same observations (rows of the data) and the same seed (or the same perms) and nperm. Names given to the arguments name the responses. A single list of such results can be given instead.

method

How the p-values of the responses are combined: "fisher" (the default), -2 \sum \log p, good when several responses have effects; "tippett", the smallest p-value, good when one response has a large effect.

tests

Names of the terms and coefficients ("coef:<name>") to combine; the default is every one that all the results have.

Details

Each response's statistic is turned into a p-value within each permuted data set (its rank among all the permutations, the observed data counted as one of them); the p-values of the responses are combined in every permuted data set, and the combined p-value is the proportion of permuted data sets whose combined statistic is at least the observed one (Pesarin and Salmaso 2010). Because the same permutation of the units is applied to every response, the correlation between the responses is kept and needs no model. Permuted data sets in which a refit failed for any response are left out.

Several tests within one family over time or over levels of a factor (a max-statistic test over time points) are available from contrastmeans with adj = "westfall" and a permlist.

Value

A data frame with one row per test: the permutation p-value of each response, the combined p-value (combined), and the p-values adjusted for the number of responses (columns adj.<response>): single-step min-p adjusted p-values (Westfall and Young 1993), which control the familywise error rate over the responses and allow for their correlation.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Pesarin, F. and Salmaso, L. (2010). Permutation Tests for Complex Data: Theory, Applications and Software. Wiley.

Westfall, P. H. and Young, S. S. (1993). Resampling-Based Multiple Testing. Wiley.

Winkler, A. M., Webster, M. A., Brooks, J. C., Tracey, I., Smith, S. M. and Nichols, T. E. (2016). Non-parametric combination and related permutation tests for neuroimaging. Human Brain Mapping, 37, 1486-1511.

See Also

permmodels, permstats

Examples

mtcars$cyl <- factor(mtcars$cyl)
p1 <- permmodels(lm(mpg ~ wt + cyl, data = mtcars), nperm = 999, type = "II", seed = 1)
p2 <- permmodels(lm(qsec ~ wt + cyl, data = mtcars), nperm = 999, type = "II", seed = 1)
permcombine(mpg = p1, qsec = p2)

Permutation Index

Description

Permutations allowed by the design: free, within blocks, of whole groups (e.g. whole plots), or of whole groups within blocks. Give the result to permmodels or permlmer (argument perms) for restricted (design-based) permutation tests; when its columns are every permutation the design allows, use exact = TRUE in permmodels().

Usage

permindex(data, block=NULL, group=NULL, nsim=4999, seed)

Arguments

data

The data the model was fitted to.

block

Optional name (in "quotes") of the blocking factor in data.

group

Optional name (in "quotes") of the factor whose levels are permuted as whole units.

nsim

The number of permutations. The default is 4999.

seed

Specify a random number generator seed, for reproducible results. The user's random number stream is left as it was.

Details

Groups are permuted as whole units, so the groups that change places (within a block, if block is given) must have the same number of rows. The data need not be sorted: before predictmeans 2.0 the indices referred to the data sorted by block and group, so they were right only for data already in that order (the permutations are the same as before for sorted data and the same seed).

Value

A matrix with one row per row of data and up to nsim columns, each a permutation of the row numbers of data (row i of the permuted data is row index[i] of data). Duplicated permutations are dropped, so there are fewer columns when the design allows fewer distinct permutations.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

permmodels, permlmer

Examples

  library(predictmeans)
  block <- rep(1:3, each=12)
  group <- rep(rep(1:3, each=4), 3)
  data <- data.frame(block, group)
  cbind(data, permindex(data, block="block", group="group", nsim=5))  
                        # Permute group as a whole within each block first, 
                        # then permute obs within each group.
  cbind(data, permindex(data, block="block",  nsim=5)) 
                        # Permute obs within each block only.
  cbind(data, permindex(data, group="group", nsim=5)) 
                        # Permute groups as a whole block first, 
                        # then permute obs within each group.
  cbind(data, permindex(data, nsim=5))  # Free permutation.

  ## A randomisation test of nitrogen in a randomised block design:
  ## permutations within blocks only
  Oats$nitro <- factor(Oats$nitro)
  fm <- lm(yield ~ Block + nitro, data = Oats)
  idx <- permindex(Oats, block = "Block", nsim = 199, seed = 1)
  permmodels(fm, perms = idx, ncore = 1)

Permutation Test of Random or Fixed Effects of Mixed Models

Description

Permutation likelihood ratio test of two nested lmer, glmer or glmmTMB models. The p-value is (b + 1)/(B + 1), b of the B permuted statistics being at least as large as the observed one; results are the same for any ncore.

Usage

permlmer(model0, model1, nperm = 999, ncore=1, plot=FALSE, seed, perms=NULL,
         method=c("auto", "working", "quantile"), ...)

Arguments

model0

lmer (or glmer, glmmTMB) model under H0 (lmer0 before 2.0); it must be nested within model1.

model1

lmer (or glmer, glmmTMB) model under H1 (lmer1 before 2.0).

...

Not used: lmer0, lmer1 (before 2.0) stop with their 2.0 spelling. permglmer() and permglmmTMB(), the same function under other names before 2.0, were removed: use permlmer().

nperm

Number of permutations; default 999.

ncore

Number of cores (default 1; before predictmeans 2.0: 3).

plot

TRUE: plot the permutation distribution of the statistic. Default FALSE.

seed

Specify a random number generator seed, for reproducible results. The user's random number stream is left as it was.

perms

Optional matrix of permutations to use instead of free ones, one row per observation and one column per permutation (e.g. from permindex); nperm is then its number of columns.

method

For GLMMs only: "working" permutes on the working (link) scale, "quantile" permutes quantile residuals of a 0/1 response and refits the GLMMs; "auto" (the default) uses "quantile" for 0/1 responses and "working" otherwise. See Details.

Details

The residuals of model0 are decorrelated with the symmetric square root of their covariance under model0, permuted, correlated again and added to the fitted values of model0 (Lee and Braun, 2012); both models are refitted to each permuted data set. The likelihood-ratio statistics are compared after rounding to 4 decimals, so an observed statistic of 0 (the tested variance estimated at 0) gives a p-value of 1. Since predictmeans 2.0 the square root is symmetric, so the results do not depend on the order of the data (1.x used the Cholesky factor). Models with the same fixed effects (tests of random effects) are compared by the REML likelihood ratio; models with different fixed effects are first refitted by ML, so the permuted statistic is the ML likelihood ratio that anova() prints in column Chisq (before 2.0 it was the ML likelihood at the REML estimates). Check: the identity permutation gives Perm-p = 1 (‘tests/testthat/test-permlmer.R’).

For GLMMs (glmer or glmmTMB; since predictmeans 2.0), method = "working" does the same on the working (link) scale: model0 is linearised at its fit (working response z = \eta + (y - \mu) d\eta/d\mu, working variance \phi V(\mu)/(a (d\mu/d\eta)^2); the covariance of z also has the random effects, as in R2_model), the decorrelated working residuals are permuted, and the statistic is the likelihood-ratio statistic of weighted linear mixed models fitted to the working responses (REML when the two models have the same fixed effects, ML otherwise). In simulations it kept the 5% level for counts and for binomial data with several trials, and was much more robust than the usual likelihood-ratio test when counts were overdispersed. For 0/1 responses the working scale fails when events are rare or clusters tiny (36% rejections at the 5% level), so method = "quantile" is used: randomised quantile residuals (Dunn and Smyth, 1996) of the response given the conditional means of model0 are permuted and mapped back to 0/1 responses, and both models are refitted (glmer fits with nAGQ = 0, for the observed data too, so the statistic can differ from the Chisq column); it kept the level (5.6-6.2%). A random effect with one level per observation (often used for overdispersion) cannot be used on the working scale; bootmodels can test it. glmmTMB models must have no zero inflation and the default dispersion model; families poisson, binomial, nbinom1, nbinom2, Gamma, gaussian and beta are handled.

Value

The anova() table of the two models with the permutation p-value in column Perm-p; for GLMMs, attribute "method" says which method was used, and attribute "failures" gives the number of refits that failed and were left out (if any).

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Oliver E. Lee and Thomas M. Braun (2012), Permutation Tests for Random Effects in Linear Mixed Models. Biometrics, Journal 68(2).

Peter K. Dunn and Gordon K. Smyth (1996), Randomized Quantile Residuals. Journal of Computational and Graphical Statistics, 5(3), 236-244.

See Also

permmodels, varcomp (test = TRUE), permindex

Examples

library(predictmeans)
## Test random effects (99 permutations to keep the example quick;
## use 999 or more in practice)
fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
fm2 <- lmer(Reaction ~ Days + (Days || Subject), sleepstudy)
fm3 <- update(fm1, . ~ . - (Days | Subject) + (1 | Subject))
anova(fm1, fm2, fm3)

permlmer(fm3, fm2, nperm=99, ncore=1)
permlmer(fm2, fm1, nperm=99, ncore=1)


## Test fixed effects
Oats$nitro <- factor(Oats$nitro)
fm0 <- lmer(yield ~ nitro+Variety+(1|Block/Variety), data=Oats)
fm <- lmer(yield ~ nitro*Variety+(1|Block/Variety), data=Oats)

permlmer(fm0, fm, nperm=99, ncore=1)

## A GLMM: do tick counts vary between locations, beyond broods?
gm1 <- glmer(TICKS ~ YEAR + scale(HEIGHT) + (1 | BROOD), family = poisson, data = lme4::grouseticks)
gm2 <- glmer(TICKS ~ YEAR + scale(HEIGHT) + (1 | BROOD) + (1 | LOCATION), family = poisson,
             data = lme4::grouseticks)
permlmer(gm1, gm2, nperm = 99, ncore = 1, seed = 1)


Permutation Tests of the Terms and Coefficients of a Model

Description

Permutation t tests of the coefficients of the fixed effects and permutation F (or chi-square) tests of the terms of a model fitted by aov, lm, glm, gls, lme, lmer, glmer or glmmTMB. p-values are (b + 1)/(B + 1): b of the B permuted statistics at least as large as the observed one. Results are the same for any ncore.

Usage

permmodels(model, nperm=4999, type=c("I", "II", "III", 1, 2, 3), 
  test_statistic=c("Chisq", "F", "LR", "Wald"), exact=FALSE, data=NULL, ncore=1, seed,
  method=c("auto", "raw", "freedman-lane"), perms=NULL, refit=TRUE, robust=FALSE, ...)

Arguments

model

Model object returned by aov, lm, glm, gls, lme, lmer, glmer or glmmTMB.

nperm

The number of permutations. The default is 4999.

type

The type of the tests: "I", "II" or "III" (or 1, 2, 3). Type III tests are those of sum-to-zero contrasts whatever contrasts the model was fitted with (as SAS Type 3); car::Anova() gives them only for models fitted with such contrasts (with R's default treatment contrasts it tests each main effect at the first level of the other factors).

test_statistic

The statistic of Type II and III tests with method = "raw": F for lm; chi-square for lme and gls; "Chisq" or "F" for lmer; "LR", "Wald" or "F" for glm. Type I tests use F. A statistic the model does not have is replaced by the one it has, with a message; with method = "freedman-lane" the F (or t) statistics are permuted and a different test_statistic is ignored with a message. The F tests of an lmer model are Kenward-Roger F tests with the observed information of the variance parameters, as in the rest of predictmeans (car::Anova() uses the expected information; the two agree for balanced data).

exact

TRUE: perms holds every permutation the design allows (a complete enumeration), so p-values are the proportion of them with a statistic at least as large as the observed one. Otherwise (the default FALSE) the observed data count as one of the permutations: p = (b + 1)/(B + 1), never 0. exact = TRUE without perms, or with repeated columns, is ignored with a warning.

data

The data the model was fitted to, when they cannot be found from the model's call (e.g. after transforming variables outside the data).

...

Not used: prt and fo (before 2.0) stop with their 2.0 spelling. Nothing is printed during the call: print() of the result shows the tables. A model whose formula is held in a variable (lm(f, data); 1.x's fo) is detected and refitted in this session only.

ncore

Number of cores (default 1; before predictmeans 2.0: 3). Each permutation has its own seed, so the results do not depend on ncore.

seed

A random number seed, for reproducible results; the user's random number stream is left as it was.

method

How the data are permuted: "freedman-lane" or "raw"; "auto" (the default) chooses the more robust one for the model class, which is "freedman-lane" for every class at present. "raw" is the scheme of predictmeans 1.x. See Details.

perms

Optional matrix of permutations to use instead of free ones, one row per observation used in the model and one column per permutation (e.g. from permindex, for permutations within blocks or of whole plots); nperm is then its number of columns. Use exact = TRUE when its columns are all the permutations the design allows.

refit

For method = "freedman-lane" with mixed models (lmer, lme, gls, and glmer, glmmTMB through their working linear mixed model): refit the model to each permuted data set (the default), so the variance parameters are estimated again each time. FALSE holds the covariance of the data at the fit (no refits, much faster), which rejects too often when the variance parameters rest on few units. In a simulation (test of the whole-plot factor of a split plot, true null, 5% level) refit = FALSE rejected 8.6%, 7.2%, 6.0% and 5.6% with 6, 12, 24 and 48 blocks (whole-plot error df 15, 33, 69 and 141), and refits 5.0%, 6.2%, 5.4% and 4.6% (Kenward-Roger 4.6% to 6.4%); at the 1% level refit = FALSE rejected up to 2.8%. So refit = FALSE suits a quick look, or a final test when the error df of the tested terms exceed about 100; otherwise keep the refits (for 199 permutations of the split plot's three terms on one core: 8 s with 6 blocks, 25 s with 48).

robust

For lm, aov and glm models with method = "freedman-lane": tests for error variances that are unequal while the model assumes them equal. The statistics are heteroscedasticity-robust (HC3 sandwich) t and Wald F statistics (DiCiccio and Romano, 2017), and the signs of the reduced model's residuals are flipped at random instead of permuted (a wild bootstrap; Davidson and Flachaire, 2008), so each residual stays with its own unit and keeps its variance. In a simulation with group SDs 3, 1, 1 (2000 data sets per case) the usual and permutation F tests rejected 19-24% of true null hypotheses at the 5% level, these tests 5-7% (normal errors) or about 9% (strongly skewed errors, against 11-14% for the HC3 F test), and 5.4% with equal variances. The tables show the robust statistics; pairs and contrasts from the result use them too (robust t, and confidence limits from robust standard errors). Type II tests match car::Anova(model, type = "II", white.adjust = "hc3"). Not with perms. The default is FALSE.

Details

With method = "auto" (the default since predictmeans 2.0) the method is chosen by model class from a simulation study (dev/permutation-plan.md in the package sources): at present Freedman-Lane for every class. Use method = "raw" for the results of predictmeans 1.x.

With method = "raw", the response is permuted for lm, aov and glm models; for gls, lme and lmer models the fitted values and the decorrelated residuals of the model are permuted together. Each permutation refits the model, and the refits are kept in permlist. The residuals are decorrelated with the symmetric square root of their covariance, so the results do not depend on the order of the data (predictmeans 1.x used the Cholesky factor, which made tests of terms that vary within blocks reject too often).

With method = "freedman-lane" (Freedman and Lane, 1983), each test has its own permutations: the residuals of the model without the tested term (for type I and II tests also without the terms that contain it; for a t test, without that coefficient) are permuted and added back to that model's fitted values, and the statistic is computed again. The statistics come from QR projections, so no model is refitted and it is fast; weights and offsets are allowed. Use it when the model has a covariate with extreme values (skewed, or with outliers) that is related to the tested term: in a simulation study, permuting the response then rejected 6 to 7% of true null hypotheses at the 5% level, and Freedman-Lane 4 to 5% (Anderson and Legendre (1999) found the same). In other designs the two methods agreed.

For mixed models with a covariate with extreme values related to the tested term, the same study found the "raw" scheme slightly liberal (6.3% at the 5% level), while the Satterthwaite F test kept the level (4.6%); prefer the Kenward-Roger or Satterthwaite F test there (anova.lmerMod or pm_joint), or method = "freedman-lane" (4.6%).

Since predictmeans 2.0, method = "freedman-lane" also handles lmer, lme and gls models, and glm, glmer and glmmTMB models. For lmer, lme and gls models (with refit = TRUE, the default) the model without the tested term is fitted, its residuals are decorrelated with the symmetric square root of its covariance, permuted, correlated again and added to its fitted values, and the model is refitted to each permuted data set; the statistics are the model's Wald t and F statistics (unadjusted covariance). One set of refits serves a term and its coefficients; pairs and contrasts in predictmeans() get one set of refits for their family (the model with all the compared means equal). With refit = FALSE the covariance of the data, V, is fixed at the fitted model: the data and the design are decorrelated with the symmetric square root of V, so least squares on them gives the same statistics, and Freedman-Lane permutations are done as for lm, without refits. That is much faster, but the permuted statistics then behave as if V were known, so comparisons whose error rests on few units rejected too many true null hypotheses in a simulation study (whole-plot factor of a split plot with 6 blocks: 8.6% at the 5% level, against 5.0% with refits; pairs of whole-plot means 6.2%). GLMs and GLMMs are first linearised at the fit (working response and working variances on the link scale, as in permlmer); GLMMs are then treated as the working linear mixed model (weights from the working variances), refitted to each permuted working response when refit = TRUE. Their t and F statistics are Wald statistics on the working scale with the dispersion estimated from the working residuals, so overdispersion affects them much less than likelihood-ratio tests (in a pilot study with overdispersed counts: 8-10% against 35% at the 5% level). For these classes the tables show these statistics and the permutation p-values; type I tests are sequential in the GLS metric (as anova() of lme4 and nlme). The result can be given to predictmeans and contrastmeans as for lm. For glmer and glmmTMB models only method = "freedman-lane" is available.

Value

A list of class "pm_permmodels": COEFFICENTS (permutation t tests of the coefficients), ANOVA (permutation tests of the terms, of the type asked for) and permlist (with method = "raw": the coefficients and covariance of each refit, for predictmeans and contrastmeans). Values are stored rounded to 4 decimals; the notes give the smallest attainable p-value, 1/(B + 1). Advice on the number of permutations is kept in attr(, "advice") (advice). With method = "freedman-lane", permlist is NULL and the result has a fourth component, perm: what is needed to test any comparison with the same permutations. Give the whole result to predictmeans or contrastmeans (argument permlist) for Freedman-Lane p-values of pairwise comparisons and contrasts. If refits fail, the number left out is in attribute "failures".

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Davidson, R. and Flachaire, E. (2008). The wild bootstrap, tamed at last. Journal of Econometrics, 146, 162-169.

DiCiccio, C. J. and Romano, J. P. (2017). Robust permutation tests for correlation and regression coefficients. Journal of the American Statistical Association, 112, 1211-1220.

Anderson, M. J. and Legendre, P. (1999). An empirical comparison of permutation methods for tests of partial regression coefficients in a linear model. Journal of Statistical Computation and Simulation, 62, 271-303.

Freedman, D. and Lane, D. (1983). A nonstochastic interpretation of reported significance levels. Journal of Business & Economic Statistics, 1, 292-298.

See Also

permlmer, permindex, permstats, permcombine, bootmodels, advice

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)
# fm <- lmer(yield ~ nitro*Variety+(1|Block/Variety), data=Oats)


## Permutation test for model terms (99 permutations to keep the example
## quick; use the default or more in practice)
permlme <- permmodels(model=fm, nperm=99, ncore=1)

## Permutation test for multiple comparisons
predictmeans(model=fm, modelterm="nitro:Variety", atvar="Variety", adj="BH",
  permlist=permlme)

## Permutation test for specified contrasts
cm <- rbind(c(-1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0),
            c(0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0))
contrastmeans(model=fm, modelterm="nitro:Variety", ctrmatrix=cm, permlist=permlme)

## The same by lmer, type II tests; refit = FALSE is much faster (no refits)
fm3 <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
permmodels(fm3, nperm = 99, type = "II", seed = 1, ncore = 1)
permmodels(fm3, nperm = 999, type = "II", seed = 1, refit = FALSE)


## Freedman-Lane permutations for a linear model with a covariate
mtcars$cyl <- factor(mtcars$cyl)
fm2 <- lm(mpg ~ wt + cyl, data = mtcars)
pfl <- permmodels(fm2, nperm = 999, type = "II", seed = 1, method = "freedman-lane")
## ... and for the pairwise comparisons of the cyl means
predictmeans(fm2, "cyl", permlist = pfl)$pairs
## Robust (HC3) statistics, for error variances that differ between the cyl groups
permmodels(fm2, nperm = 999, type = "II", seed = 1, robust = TRUE)

Effect Sizes and Model Checks from Permutations

Description

Uses the permuted statistics kept by permmodels to give, for each term and coefficient, a standardised effect size and a check of the usual parametric test against the permutation distribution.

Usage

permstats(x, conf_level = 0.95, ...)

Arguments

x

A result of permmodels with Freedman-Lane permutations (method = "auto", the default, or "freedman-lane").

conf_level

The check of the parametric test is at the significance level 1 - conf_level (default 0.95, i.e. 0.05; level = 0.05 before 2.0).

...

Not used: level (before 2.0) stops with its 2.0 spelling.

Details

Every permuted data set comes from the model without the tested term (Freedman-Lane), so the permuted statistics show how the statistic behaves when that term has no effect but everything else in the data is kept. Comparing the parametric p-value with the permutation p-value, and param.size with 1 - conf_level, shows whether the usual test can be trusted for these data. For mixed models the permuted statistics are Wald statistics (unadjusted covariance), so param.size checks the Wald F with the given df, not the Kenward-Roger test.

Value

A data frame with one row per term and coefficient (rows "coef:<name>"):

statistic

the observed statistic: F for terms, |t| for coefficients (robust ones with robust = TRUE).

df1, df2

numerator and denominator df of the usual parametric test: the residual df for lm, aov, glm and gls, Satterthwaite df for lmer, nlme's df for lme, and Inf (Wald chi-square) for glmer and glmmTMB.

p.param

the parametric p-value of the observed statistic with these df.

p.perm

the permutation p-value (as in the tables of permmodels()).

ses

the standardised effect size, (observed - mean of the permuted statistics) / their standard deviation (Gotelli and McCabe 2002): how far the observed statistic lies from what the permutations give when the effect is absent, in standard deviations.

param.size

the proportion of permuted data sets in which the parametric test rejects at 1 - conf_level. The permuted data sets have no effect for the tested term, so this is the type I error rate of the parametric test for data like these: close to 1 - conf_level when the parametric reference distribution suits the data, clearly above it when the parametric test is too liberal here (for example with unequal variances, overdispersion or few groups), below it when it is conservative. With few permutations it is rough (its standard error is about sqrt(a (1 - a) / nperm), a = 1 - conf_level).

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Gotelli, N. J. and McCabe, D. J. (2002). Species co-occurrence: a meta-analysis of J. M. Diamond's assembly rules model. Ecology, 83, 2091-2096.

See Also

permmodels, permcombine

Examples

mtcars$cyl <- factor(mtcars$cyl)
fm <- lm(mpg ~ wt + cyl, data = mtcars)
pfl <- permmodels(fm, nperm = 999, type = "II", seed = 1)
permstats(pfl)

Box-Cox and Yeo-Johnson Transformations of a Response

Description

Power transformations to use for the response in a model formula, e.g. lm(pm_boxcox(y, 0.25) ~ A). predictmeans and covariatemeans recognise them (as they recognise log(y), log(y + c), log10(y), log2(y), log1p(y), sqrt(y), y^p, 1/y, qlogis(y) and asin(sqrt(y))) and give the means back-transformed to the original scale as well; bias_adjust = TRUE there gives the mean rather than the median of the original scale.

Usage

pm_boxcox(y, lambda)
pm_yeojohnson(y, lambda)

Arguments

y

A numeric vector; positive for pm_boxcox(), any values for pm_yeojohnson().

lambda

The power: one number. Box-Cox: 1 leaves the shape of y as it is, 0.5 is like a square root, 0 is the logarithm, -1 like a reciprocal. pm_check reports the value the data suggest for an lm fit.

Details

Box-Cox: (y^\lambda - 1)/\lambda, and \log y for \lambda = 0. Yeo-Johnson (2000): the same for y + 1 when y \ge 0, and -((1 - y)^{2 - \lambda} - 1)/(2 - \lambda) (-\log(1 - y) for \lambda = 2) when y < 0, so zero and negative values are allowed.

Choose a transformation from the residuals of the model, not from the raw response, and prefer a generalized linear (mixed) model for counts and proportions.

Value

The transformed values.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Box, G. E. P. and Cox, D. R. (1964), An analysis of transformations, Journal of the Royal Statistical Society B, 26(2), 211-252.

Yeo, I.-K. and Johnson, R. A. (2000), A new family of power transformations to improve normality or symmetry, Biometrika, 87(4), 954-959.

See Also

predictmeans, pm_check

Examples

  library(predictmeans)
  Oats <- as.data.frame(nlme::Oats)
  Oats$nitro <- factor(Oats$nitro)
  fm <- lm(pm_boxcox(yield, 0.5) ~ Block + nitro, data = Oats)
  predictmeans(fm, "nitro", plot = FALSE)$means

Checks of a Fitted Model

Description

A table of checks of a model's assumptions and structure, grouped in sections, with a plain note on each: the fit itself (singular or not converged); the residuals (outliers, influence, normality, a transformation); the variance (equal across factor levels, constant with the fitted values); the distribution of generalized models (over- and underdispersion, excess zeros, separation); the design (balance and empty cells, aliasing, collinearity, few levels of a random effect); and the terms (interactions, straight lines). For any model that predictmeans handles.

Usage

pm_check(model, plot = FALSE)

Arguments

model

A fitted model, as for residplot.

plot

TRUE: also draw the diagnostic plots of residplot.

Details

The checks inform; they do not decide. Rows marked ! are worth a look at the plots of residplot; rows marked i are information. Keep the terms the design calls for (blocks, whole plots, the treatment structure): dropping a term because its test is not significant makes the later tests and intervals too optimistic. Tests of normality and of equal variances reject small departures in large data sets and miss large ones in small data sets; the plots say how large a departure is.

Fit

singular fits (a variance component estimated as zero) and convergence warnings.

Outliers

residuals beyond 3 (of the residuals residplot uses: standardized, normalized or randomized quantile), against the number expected for normal residuals; worth a look when that many, or one as large as the largest (Bonferroni over the observations), has probability below 0.01.

Influence

(lm, aov, glm) the largest Cook's distance; above 0.5 is worth a look (CookD for mixed models).

Normality

Shapiro-Wilk tests of the residuals and of each term's random effects (intercepts).

Transformation of the response

(lm and aov with a positive response that is not transformed in the formula) the Box-Cox power the residuals favour: the profile likelihood estimate of \lambda and its 95% interval (Box and Cox, 1964; as MASS::boxcox()). Worth a look when the interval leaves out 1 (no transformation); the note names the usual transformation within the interval.

Equal variances

for each factor: the ratio of the largest to the smallest standard deviation of the residuals within its levels, and the Brown-Forsythe test (ANOVA of the absolute deviations from the medians).

Spread vs fitted values

(gaussian models) Spearman correlation of the absolute residuals with the fitted values; worth a look when |\rho| \ge 0.2 and p < 0.01 (the variance grows with the mean).

Dispersion

(Poisson, binomial with more than one trial, negative binomial; glm, glmer, glmmTMB) Pearson chi-square / residual df, about 1 when the variance function is right; overdispersion (ratio > 1.5, p < 0.01) makes SEs too small, underdispersion (ratio < 0.7, p < 0.01) too large. For mixed models the residual df counts the variance parameters, an approximation. A 0/1 response carries no information on dispersion; for families with an estimated dispersion (Gamma, quasi) its estimate is shown.

Zero counts

(Poisson, negative binomial) the observed zeros against those simulated from the fitted model (200 simulations, fixed seed; the user's random numbers are not changed); worth a look when there are more (p < 0.01).

Separation

(binomial) fitted probabilities of 0 or 1, or coefficients beyond 10 on the logit scale or with standard errors above 50: the estimates and Wald tests of these terms are unreliable.

Balance of cells

of the crossed fixed factors: balanced, unbalanced or with empty cells; unbalanced data make Type I, II and III tests differ (see anova.lmerMod, section 'Which type of test').

Estimability

coefficients dropped as aliased (empty cells or confounded factors).

Collinearity

(models of main effects only) the generalized variance inflation factor of each term, GVIF^{1/(2 df)} (Fox and Monette, 1992); above \sqrt{10} is worth a look.

Random-effect levels

a grouping factor with fewer than 5 levels: its variance is poorly estimated.

Interaction

the Type III test of each interaction term (as permmodels(type = "III")).

Straight line

for a factor with numeric levels and at least three of them: the joint test of the polynomial contrasts above the linear one (with the actual spacing of the levels), from pm_joint.

Value

A data frame of class "pm_check": section, check, result, p.value, look, status ("!" worth a look, "i" information, "OK") and note; printed by section with the notes below. summary() keeps only the rows worth a look. The rows worth a look are also kept as advice (advice).

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Fox, J. and Monette, G. (1992). Generalized collinearity diagnostics. Journal of the American Statistical Association, 87, 178-183.

See Also

residplot, CookD, advice, pm_boxcox

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
pm_check(fm)

# counts: overdispersion
gm <- glm(breaks ~ wool * tension, family = poisson, data = warpbreaks)
pm_check(gm)
summary(pm_check(gm))

Supporting a New Model Class

Description

Kmatrix, predictmeans, contrastmeans and covariatemeans get everything they need from a model through these seven generics. Their default methods work for any model class with the usual methods (coef, vcov, terms, df.residual, family), so many classes need no extra code. For a class that lacks one of these, or needs something special, write a method for the corresponding generic only; nothing inside predictmeans needs to change.

Usage

pm_coef(model, ...)
pm_vcov(model, ...)
pm_basis(model, newdata, ...)
pm_df(model, L, ...)
pm_linkinv(model, ...)
pm_contrasts(model, ...)

Arguments

model

A fitted model.

newdata

A data frame of predictor values (the reference grid).

L

A matrix of linear functions of the coefficients, one row per contrast or mean.

...

Further arguments. Kmatrix() passes terms, contrasts and xlev to pm_basis(), and exclude for gam models.

Details

pm_coef(model)

Named fixed-effect estimates, with NA for aliased coefficients. Default: coef(model); methods for lme, merMod and glmmTMB return the fixed effects.

pm_vcov(model)

Covariance matrix of the non-aliased estimates. Default: vcov(model).

pm_basis(model, newdata, ...)

Design matrix of the fixed effects for newdata, with columns named as in pm_coef(model): the columns are matched to the coefficients by name, and a coefficient without a column stops with a message (a column for an aliased coefficient may be there or not). Default: model.matrix() of the model's terms (with their stored predvars, so poly(), ns(), scale() etc. use the fitted basis), contrasts and factor levels. The gam method uses the linear predictor matrix of package mgcv.

pm_data(model)

The data used to fit the model. The default method (see pm_data) finds them from the data argument of the call, getData() or the model frame; Kmatrix() uses a pm_data() method only when the class has its own.

pm_df(model, L)

Denominator degrees of freedom for each row of L, or NULL (the default) to use the model's single residual df: df.residual(model), or Inf (normal-based) when there is none. Kenward-Roger df for lmer and the rules of nlme for lme are built in.

pm_linkinv(model)

Inverse link function used to back-transform the means, or NULL for none. Default: the inverse link of family(model) unless it is the identity.

pm_contrasts(model)

The contrasts of the factors used in the fit, as for the contrasts.arg argument of model.matrix(). Default: those of model.matrix(model), else model$contrasts; a method is only needed for a class that has neither.

The model also needs a terms() method for its fixed effects (used to find the variables in the model), and its call (getCall()) or a pm_data() method so that the data can be found.

Value

As described in Details.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

Kmatrix, pm_data

Examples

  library(predictmeans)
  # A made-up model class that wraps lm() and has only four methods. (Methods are
  # found where predictmeans looks for them: in a package's namespace or, as
  # here, in the global environment; registerS3method() also works.)
  fit_mymodel <- function(formula, data) {
    structure(list(fit = lm(formula, data), call = match.call()), class = "mymodel")
  }
  registerS3method("coef", "mymodel", function(object, ...) coef(object$fit))
  registerS3method("vcov", "mymodel", function(object, ...) vcov(object$fit))
  registerS3method("terms", "mymodel", function(x, ...) terms(x$fit))
  registerS3method("df.residual", "mymodel", function(object, ...) object$fit$df.residual)

  Oats <- as.data.frame(nlme::Oats)
  Oats$nitro <- factor(Oats$nitro)
  m <- fit_mymodel(yield ~ Block + nitro*Variety, data = Oats)
  predictmeans(m, "nitro")$means

  # Degrees of freedom of its own, e.g. normal-based:
  registerS3method("pm_df", "mymodel", function(model, L, ...) rep(Inf, nrow(L)))
  predictmeans(m, "nitro")$means

Data of a Fitted Model, with the Response on Both Scales

Description

pm_data() returns the rows used to fit a model (after subset and missing values), with the response on the scale of the model and on the original scale: .y is the response as modelled (e.g. log(y + 1); for a GLM the observed response, as a proportion for cbind(successes, failures)), and .y_orig the response on the original scale (y), taken from the data or, when only the transformed response is available, computed with the inverse transformation. A transformation given to predictmeans as trans (for a response transformed before the fit) is used the same way. It is also the generic through which a new model class can say where its data are (see pm_coef).

Usage

pm_data(model, ...)

## Default S3 method:
pm_data(model, data = NULL, trans = NULL, ...)

Arguments

model

A fitted model, or a semireg fit.

...

Not used.

data

Optional: the data the model was fitted to, when they cannot be found from the model.

trans

Optional: a function that back-transforms the response (as trans of predictmeans), used when the model formula has an untransformed response.

Value

A data frame with the variables of the data, .y, .y_orig and .weights (prior weights, when there are any), and attribute "response": a list with expr (the response as written, e.g. "log(y + 1)"), name (the response variable, e.g. "y"), scale of the model's means ("identity", "transformed" or "link"), link, family and back (what back-transforms the means: "link", "formula", "trans" or NA).

Examples

  oats <- as.data.frame(nlme::Oats)
  fm <- lm(log(yield + 1) ~ Variety, data = oats)
  d <- pm_data(fm)
  head(d[c("yield", ".y", ".y_orig")])
  attr(d, "response")

Joint F Tests of Contrasts among Means (Slices)

Description

F tests of sets of contrasts among the predicted means of a model term. With by, the means of the term are compared within each level of the by factor(s): the test of nitro within each Variety, as SAS LSMEANS nitro*Variety / SLICE=Variety or emmeans::joint_tests(model, by = "Variety"). With ctrmatrix, all its rows are tested together.

Usage

pm_joint(model, modelterm, by = NULL, ctrmatrix = NULL,
         df_method = c("auto", "Kenward-Roger", "Satterthwaite", "containment",
           "between-within", "KR-expected", "KR-average", "inner-outer", "residual"),
         weights = c("equal", "proportional", "outer", "cells", "flat"), vcov = NULL)

Arguments

model

A fitted model, as for predictmeans.

modelterm

Name (in "quotes") of the model term whose means are compared, e.g. "nitro:Variety".

by

Optional name(s) of factor(s) of modelterm: test the differences among the means within each of their levels. Without by and ctrmatrix, all differences among the means of modelterm are tested.

ctrmatrix

Optional contrast matrix over the means of modelterm (as for contrastmeans, e.g. from contrast_family or specify_contrast); its rows are tested together.

df_method

For lmer models ("between-within" also for lme and gls): the denominator df (see Details).

weights

How the means average over other factors, as in predictmeans.

vcov

Optional covariance of the coefficients, as in predictmeans: the F statistic is then the Wald F with this covariance, and the denominator df those of the model's own test.

Details

The F statistic and its denominator degrees of freedom follow the model:

lmer

Kenward-Roger (the default for REML fits): the scaled F test of Kenward and Roger (1997) with the observed information of the variance parameters, as SAS DDFM=KR; Satterthwaite (the default for ML fits): as lmerTest::contest(joint = TRUE); containment: the Wald F with the containment df of modelterm.

KR-expected

(lmer, lme, gls) Kenward-Roger with the expected information, as pbkrtest::KRmodcomp() (see predictmeans).

KR-average

(lmer, lme, gls) Kenward-Roger with the average information: Genstat's REML df (Genstat's F statistic is Kenward-Roger's scaling factor times the Wald F of the unadjusted covariance).

between-within

(lmer, lme, gls) the Wald F with the between-within df of modelterm (SAS DDFM=BETWITHIN; see predictmeans).

lme, gls with df_method = "Satterthwaite", "Kenward-Roger", "KR-expected" or "KR-average"

as for lmer (Satterthwaite df of the F test, lmerTest's rule).

lme, gls

Kenward-Roger for REML fits and Satterthwaite for ML fits (the defaults), as for lmer; with df_method = "containment" the Wald F with nlme's df of modelterm (as anova(); "containment (nlme)") or the residual df (gls).

glm with a known dispersion

(Poisson, binomial, negative binomial) the Wald chi-square / df (denominator df Inf); df_method = "residual": the residual df, as predictmeans 1.x.

other models

the Wald F with the residual df (normal-based when there is none).

Contrasts that are linear combinations of others are dropped, so df1 is the rank of the set. Without ctrmatrix, each set is written as each level against the last (SAS's Type 3 basis): Wald and Kenward-Roger F tests do not depend on the basis, but the Satterthwaite df of a test with several df do (Fai and Cornelius 1996), and with this basis they equal SAS's. emmeans::joint_tests() gives a slightly different Kenward-Roger test (the unscaled F with its own df).

Value

A data frame with one row per test: the by levels (if any), df1, df2, F.ratio and p.value. Attribute "df_method" says how df2 was found.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Kenward, M. G. and Roger, J. H. (1997), Small sample inference for fixed effects from restricted maximum likelihood, Biometrics, 53, 983-997.

See Also

contrastmeans, contrast_family, predictmeans

Examples

  library(predictmeans)
  Oats$nitro <- factor(Oats$nitro)
  fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
  # nitrogen within each variety (SAS SLICE)
  pm_joint(fm, "nitro:Variety", by = "Variety")
  # varieties within each nitrogen level
  pm_joint(fm, "nitro:Variety", by = "nitro")
  # a set of contrasts: linear and quadratic nitrogen trends together
  pm_joint(fm, "nitro", ctrmatrix = contrast_family(Kmatrix(fm, "nitro"), "poly", max_degree = 2))

Slopes of a Covariate by Group

Description

The slope (rate of change) of the fitted response in a numeric covariate within each level of a model term, with standard errors, degrees of freedom, confidence limits and tests, and pairwise comparisons of the slopes, as emmeans::emtrends() and SAS ESTIMATE statements on slope terms.

Usage

pm_slopes(model, covariate, modelterm, at = NULL, conf_level = 0.95, adj = "none",
          df_method = c("auto", "Kenward-Roger", "Satterthwaite", "containment",
            "between-within", "KR-expected", "KR-average", "inner-outer", "residual"),
          vcov_adjust = TRUE,
          weights = c("equal", "proportional", "outer", "cells", "flat"),
          vcov = NULL, ...)

Arguments

model

A fitted model, as for predictmeans.

covariate

Name (in "quotes") of the numeric covariate.

modelterm

Name (in "quotes") of the factor term whose levels get a slope each, e.g. "Variety".

at

The value of the covariate where the slopes are taken (matters only when the covariate enters the model non-linearly); the default is its mean.

conf_level

Confidence level of the limits, the default is 0.95 (level = 0.05 before 2.0).

adj

Adjustment of the p-values of the pairwise comparisons of slopes, as in predictmeans.

df_method, vcov_adjust, weights, vcov

As in predictmeans.

...

Not used: level (before 2.0) stops with its 2.0 spelling.

Details

The slopes are on the scale of the linear predictor. They come from the reference grid of Kmatrix: the change in the K matrix between at - h and at + h, divided by 2h with h = 0.0001 times the standard deviation of the covariate. This is exact when the covariate enters the model linearly (also through interactions) and a central difference for poly(), splines and smooths, whose slope depends on at. Standard errors and degrees of freedom follow predictmeans: for models fitted by REML (lmer, lme, gls) Kenward-Roger (with the adjusted covariance when vcov_adjust = TRUE); with one df per term (containment, between-within, nlme's df) the smallest df of the terms with the covariate; otherwise the residual df.

Value

An object of class "pm_slopes", a list in the layout of predictmeans (tidy() and as.data.frame() return its tables, what = "slopes" or "pairs"):

slopes

one row per level of modelterm: the factor columns, estimate (the slope), std.error, df, statistic (t), p.value (of slope = 0), conf.low and conf.high.

pairs

one row per pair of levels: level1, level2, estimate (slope of level1 minus slope of level2), std.error, df, statistic, p.value, p.adj, conf.low, conf.high and, with the adjustments that have them (tukey, bonferroni, sidak, scheffe, mvt), adj.conf.low, adj.conf.high: simultaneous limits that leave out 0 exactly when p.adj is below 1 - conf_level.

settings

modelterm, covariate, at, level, adjust, df_method, vcov_adjust, vcov, model_class, version.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

covariatemeans, predictmeans, advice

Examples

  library(predictmeans)
  Oats <- as.data.frame(nlme::Oats)
  fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
  sl <- pm_slopes(fm, "nitro", "Variety", adj = "tukey")
  sl
  as.data.frame(sl, what = "pairs")

Predicted Means of a Linear Model

Description

Predicted means, their standard errors (SE), standard errors of differences (SED) and least significant differences (LSD) for aov, lm, glm, gls, lme, lmer, glmer, glmmTMB, gam and semireg fits, with pairwise comparisons and permutation tests. Plots are drawn from the result with link{autoplot.predictmeans}; link{advice} reads the notes made for this fit and data.

Usage

predictmeans(model, modelterm, data=NULL, pairwise=NULL, atvar=NULL, adj="none",
  conf_level=0.95, covariate=NULL, meandecr=NULL, letter_ci=FALSE, trans = I,
  permlist=NULL,
  ncore=1, cov_reduce=mean, exclude=NULL, vcov_adjust=TRUE,
  weights=c("equal", "proportional", "outer", "cells", "flat"),
  df_method=c("auto", "Kenward-Roger", "Satterthwaite", "containment",
    "between-within", "KR-expected", "KR-average", "inner-outer", "residual"),
  vcov=NULL,
  equivalence=NULL, bias_adjust=FALSE, sigma=NULL, average=c("link", "response"),
  mean_type=c("conditional", "overall"), ...)

Arguments

model

Model object returned by aov, lm, glm, gls, lme, lmer, glmer, glmmTMB and gam (package mgcv), or a semireg fit. An aov model with Error() strata is analysed by strata, as Genstat's ANOVA: each comparison uses the mean squares of the strata it draws on, with Satterthwaite's df across strata (settings$df_method "multistratum"); standard errors of single means include the block stratum. With missing values in an orthogonal design (rows whose response is NA, or a few combinations of the design factors absent) they are estimated as Genstat's ANOVA does (the residual sum of squares of the lowest stratum made smallest; the residual df reduced) and the completed design is analysed by strata, with exact standard errors (Genstat's are those of the complete design); a message says that REML (lmer() with the Error() terms as random effects) uses the information in all strata and is the better analysis when plots are missing. For a semireg fit the means include the smooth terms (as semipred), at the covariates' means or at the values of covariate (a named vector, e.g. c(construction.date = 1980)); the result holds only the means, pairs and settings tables, with any adj. For gaussian fits the tests are t tests with Satterthwaite df for the combination of fixed and smooth coefficients (the means include the smooths' random effects; SAS gives such df to estimates that involve random effects), from the design's variance components and the residual with the smoothing parameters held at their estimates (as semipred); for generalized fits the inner-outer df of the design's strata (the GLMM default; normal-based without random terms besides the smooths).

modelterm

Name (in "quotes") for indicating which factor term's predicted mean to be calculated: factors of the model joined by ":", e.g. "A" or "A:B". A combination of factors that is not a term of the model can be asked for too (e.g. "A:B" for y ~ A + B): its means are the sums of the factors' effects that the model implies (a note says so), which gives a table of predictions for every combination, also those without data. Covariates are set with covariate.

data

The data used to fit the model; needed in some cases, e.g. when a variable is transformed in the model formula.

pairwise

What is printed: TRUE shows the pairwise p-value matrices (t values above the diagonal) and the letter groups; FALSE hides them; NULL (the default) shows them when comparisons are asked for (adj, atvar, permlist or letter_ci), as before 2.0. It does not change what is computed: the pairs table (every difference, SE, df, p-value, adjusted p-value and limits) is made whenever comparisons are asked for, also with pairwise = FALSE, and otherwise for up to 100 means. With more means (e.g. several hundred lines of a breeding trial) and no comparison asked for, the means, their SEs and the SED and LSD summaries (maximum, minimum, average) are computed from the covariance of the means, without a row per pair (300 means: about a second), and pairs is NULL; pairwise = TRUE or adj compares all the pairs. No letter groups are made for more than 100 means. options(predictmeans.max_means = ) changes the limit of 100. (Before 2.0 the default was FALSE, and adj or atvar turned it on.)

atvar

Factor(s) of modelterm within whose levels the pairs are compared (one or two names, or "A:B"); each level is a family for adj, and the LSDs are those of the pairs within it.

adj

Name (in "quote") for indicating a method for adjusting p-values of pairwise comparisons. The choices are "none", "tukey", "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "sidak", "scheffe" and "mvt". "sidak", "scheffe" (rank of the family: number of means - 1) and "mvt" (single-step multivariate t, the exact counterpart of SAS ADJUST=SIMULATE; needs package mvtnorm) are as in emmeans. Adjusted p-values use each pair's own df (as SAS ADJDFE=ROW; SAS's default ADJDFE=SOURCE uses the df of the term's F test instead, which differs when the pairs' df differ). With permlist, "tukey" and "mvt" give the single-step max-|t| adjustment of the permutation p-values (the permutation version of Tukey's test: each pair's |t| is compared with the largest |t| of the family in each permuted data set), and "westfall" the step-down max-|t| of Westfall and Young (1993), which is uniformly more powerful; both use the correlation between the comparisons. "westfall" needs permlist; "scheffe" is not available with it. The default method is "none"; letter case does not matter ("Tukey" works). Confidence limits that agree with the adjusted p-values are in the columns adj.conf.low and adj.conf.high of pairs. The printed LSDs go with the p-values: the SED times the critical value of the method, for the same family of pairs (all pairs, or the pairs within a level of atvar): t for "none", the studentized range divided by \sqrt{2} for "tukey" (the HSD), t at the adjusted level for "bonferroni" and "sidak", and the Scheffe and multivariate t values. So a difference is beyond its LSD exactly when its adjusted p-value is below 1 - conf_level. The step-wise methods ("holm", "hochberg", "hommel", "BH", "BY", "fdr") have no critical value for all pairs: their LSDs are not adjusted and a note with the LSDs says so. (Before 2.0 only "bonferroni" adjusted the LSDs, with all the pairs as family also with atvar.)

conf_level

The confidence level of the confidence limits; the tests, LSDs and letters are at the significance level 1 - conf_level. The default is 0.95 (level = 0.05 before 2.0).

covariate

The values of covariates at which the means are predicted: a named list or vector, e.g. list(x = 2, z = 0.3) (covariates not named are at their means), or an unnamed numerical vector with one value for each covariate of the model, in their order. The default values are the means of the covariates (see cov_reduce). For means along the values of a covariate use covariatemeans.

meandecr

Logical: order the letters of mean_table by decreasing (TRUE) or increasing (FALSE) means. The default NULL keeps the order of the factor levels.

letter_ci

A logical variable to indicate printed letters for multiple comparisons by whether or not the comparison intervals of the means overlap (the default is FALSE). The comparison intervals are mean \pm c\,SE with c = t \times SED/(SE_1 + SE_2), averaged over the pairs compared, so that two means differ at 1 - conf_level when their intervals do not overlap: 83.4% intervals for independent means with equal SEs and a 5% test, wider when the SEs differ, narrower when the means are correlated as in most mixed models (Goldstein and Healy, 1995; Maghsoodloo and Huang, 2010; Afshartous and Preston, 2010). They are shown as LL and UL in mean_table, labelled with their level, and the note under the table says how many pairs are judged differently by their own tests when the SEDs differ. The comparisons are at the significance level 1 - conf_level (default 0.05), adj is "none", and with atvar the letters compare the means within each atvar group. (Before 2.0 the intervals were 83.4% confidence intervals whatever the design, and level set their level, 0.166 by default.) The comparison intervals are in every result: columns comparison.low and comparison.high of means, and autoplot(interval = "comparison").

trans

A function object for calculating the back transformed means, e.g. trans=exp. When it is not given and the response is transformed in the model formula (log(y), log(y + c), log10(y), log2(y), log1p(y), sqrt(y), y^p, 1/y, qlogis(y), asin(sqrt(y)), pm_boxcox(y, lambda), pm_yeojohnson(y, lambda)), the inverse is used, constant included, and a message says so; trans = I keeps the model scale only. Models with a link (glm, glmer, glmmTMB) are back-transformed with its inverse, unless trans is given: then trans is used (with a message), and trans = I keeps the link scale, as in covariatemeans (before 2.0 a given trans was silently replaced by the inverse link). What the back-transformed mean is depends on the model: for a GLM the mean; for a GLMM the response of a typical cluster (random effects at zero); for a transformed response the median of the original scale (the geometric mean for a log). bias_adjust = TRUE gives the mean in the last two cases; settings$back_transform and summary() say which it is.

...

Not used: arguments removed in 2.0 (e.g. level, Df, plot, plot_args, plottitle as an argument of its own) stop with their 2.0 spelling (see vignette("migrating")); other names are an error.

permlist

A list from permmodels: the pairs are then tested by permutation, with p-value (b + 1)/(B + 1) (b of the B permuted statistics at least as extreme as the observed one), and df_method is not used. With the result of permmodels(method = "freedman-lane") (lm and aov models), each pair is tested by Freedman-Lane permutations of the model in which that pair's means are equal. With a permlist, vcov_adjust is not used: the observed t statistics are compared with those of the permuted refits, which use the unadjusted covariance. The confidence limits of each mean are the model's t limits at conf_level (the permutation tests are of the comparisons; before 2.0, mean +/- 2 SE).

ncore

Number of cores for parallel computing when permlist != NULL, the default value is 1 (before predictmeans 2.0: 3). Results are the same for any ncore.

cov_reduce

How covariates that are not varied are handled when building the predicted means: a function such as mean (the default) or median, or "average" to average the predictions over the observed covariate values (e.g. means adjusted for a spatial smooth in a gam). See Kmatrix.

exclude

For gam models: smooth terms to leave out of the predictions. The default excludes random-effect smooths. See Kmatrix.

vcov_adjust

For models fitted by REML (lmer, lme, gls) with Kenward-Roger df: if TRUE (the default), standard errors use the Kenward-Roger adjusted covariance matrix of the fixed effects, as SAS DDFM=KR and emmeans do, to go with the Kenward-Roger degrees of freedom. FALSE uses the unadjusted covariance and reproduces results of predictmeans 1.x. It has no effect for other models.

weights

Passed to Kmatrix: how the cells of the factors that are not in modelterm are weighted when averaging over them: "equal" (the default; equal weights), "proportional" (weights proportional to the frequencies of those cells in the data, the same for every mean, as SAS LSMEANS / OM), "outer" (products of each factor's own frequencies), "cells" (each mean weights the cells by their own frequencies) or "flat" (equal weights over the non-empty cells). The definitions are those of emmeans. Empty cells (combinations of interacting factors without data, not those absent by design, as for nested factors): with "equal", a mean that averages over them is the average of its observed cells (as predictmeans 1.x, and ASReml and Genstat with PRESENT), with a warning naming those means. Two such means average over different cells, so their difference would also carry the effects of the other factors; a pair with such a mean is therefore compared on the cells both means have (column over of pairs; NA, over = "none", when they have none). Only factors whose effects the two means share are matched: with Sample_date/Farm in the model, two dates are not matched on farms (each date has its own farm effects), but two treatments at one date are. In simulations comparing the averages rejected 8-78% of true null hypotheses at the 5% level when the other factor had an effect, the common cells 4-6% (dev/review-defaults.md in the package sources). contrastmeans() and pm_joint() do the same. A cell is a combination of the factors of one interaction term: factors that do not interact do not make cells together, and a combination of them without data is estimated by the (additive) model. Confounded factors (two factors that share no term and do not occur in all combinations: a factor nested in another only in the data, a spray volume used with one droplet size, each pasture on one farm) have no mean over all their combinations; the means then average over the combinations that exist, with a warning that names the two factors. Three ways say what is wanted: the nesting in the formula (G/T) or the model without the factor that adds nothing give the same means (equal weights over the combinations that exist); weights = "cells" weights the combinations by their numbers of observations. See vignette("missing-cells", package = "predictmeans").

df_method

Denominator degrees of freedom, by method or as one number (a fixed df, Df before 2.0), e.g. df_method = 10. For lmer models "auto" (the default) uses Kenward-Roger for REML fits and Satterthwaite for ML fits. Kenward-Roger uses the observed information of the variance parameters, as SAS PROC MIXED DDFM=KR; it stays valid with missing values, where the expected information ("KR-expected", as pbkrtest and emmeans) is not: in simulations (dev/sim-df/ in the package sources) F tests of repeated measures with missing values rejected 6% of true hypotheses at the 5% level with the observed information and 8.5% with the expected. The two agree in balanced designs. "KR-average" uses the average information of the REML iterations of Genstat and ASReml (Gilmour, Thompson and Cullis 1995) and gives Genstat's REML df; Genstat's SEDs are the unadjusted ones (vcov_adjust = FALSE). "containment" gives the SAS DDFM=CONTAIN df: the smallest rank contribution to [X Z] of the random effects that contain modelterm, or the residual df when none does; all means and comparisons of the term then share that df, and the unadjusted covariance is used unless vcov_adjust = TRUE is given. "between-within" gives the SAS DDFM=BETWITHIN df, for lmer, lme and gls models: the subject is the coarsest random-effect grouping (lmer, lme) or the grouping of the correlation structure (gls); an effect constant within subjects gets the between-subject df, and the others the df of their subject-by-effect interaction (for example Block x Variety in a split plot); with an unstructured covariance (gls with corSymm) and no random effects every effect gets the between-subject df, as in SAS. Checked against SAS PROC MIXED. As for containment, the unadjusted covariance is used unless vcov_adjust = TRUE is given. For lme and gls models fitted by REML, "auto" is Kenward-Roger too (with adjusted standard errors), for any correlation and variance structure: in simulations the residual df (gls) rejected 16% of true hypotheses in F tests of unstructured repeated measures (24% with missing values), Kenward-Roger 4-6%. "Satterthwaite" is also available (the covariance of the variance parameters from the Hessian of the REML log-likelihood, as SAS; its F tests are liberal when the covariance has several parameters), and "containment" gives nlme's df (lme) or the residual df (gls), as predictmeans 1.x. All are checked against SAS PROC MIXED. ML fits of lme and gls use Satterthwaite from the ML log-likelihood, as ML lmer fits (lmerTest); before 2.0 they used nlme's or the residual df (df_method = "containment"). In simulations of ML gls fits with an unstructured covariance the residual df rejected 6.9% (t) and 9.3-11.7% (F) of true null hypotheses, Satterthwaite 5.5% and 6.3-8.8%; fit by REML for Kenward-Roger, which held 5%. For GLMMs (glmer, glmmTMB) "auto" is "inner-outer": the df of the level of the random effects at which each effect varies, nlme's rule (Pinheiro and Bates 2000), computed from the design and extended to crossed random effects; a contrast gets the smallest df of the coefficients it uses, and the means of a term the df of the term. In simulations it rejected 6-8% of true hypotheses for effects that vary between clusters, where the residual df ("residual", predictmeans 1.x) rejected 8-15%; bootmodels() is the check with few clusters. "containment" and "between-within" are also available for glmer, and "inner-outer" for lmer and lme. glm models with a known dispersion (Poisson, binomial, negative binomial) get z tests ("asymptotic (z)"), as emmeans and SAS GLIMMIX; "residual" gives the t tests with the residual df of predictmeans 1.x, which were conservative in simulations (0.3-4.5% of true null hypotheses rejected at the 5% level, z tests 3.6-5.7%). Other choices are ignored for other model classes.

vcov

Optional covariance of the coefficients to use instead of the model's. For lm, aov and glm models: "HC0", "HC1", "HC2" or "HC3" (heteroscedasticity-consistent, as sandwich::vcovHC()), or a one-sided formula naming a cluster variable of the data, e.g. ~ Block (cluster-robust CR1, as sandwich::vcovCL()). For any model: a covariance matrix of the coefficients, or a function that returns one from the model (for mixed models e.g. from the clubSandwich package). The degrees of freedom stay those of the model (the residual df; for lmer Kenward-Roger or Satterthwaite df computed from the model), and vcov_adjust is not used. With a permlist, vcov is not used (for robust permutation tests see permmodels(robust = TRUE)). The default NULL uses the model's covariance.

equivalence

Optional equivalence margins for equivalence tests (two one-sided t tests, TOST) of the differences: a positive number d (equivalence region -d to d) or c(lower, upper), on the scale of the comparisons (the link scale for GLMs: e.g. log ratios). The TOST p-value is the larger of the two one-sided p-values; below 1 - conf_level, the difference lies within the margins (as emmeans' test(..., side = "equivalence")). Not adjusted for multiplicity; with a permlist it is t-based (normal-based in contrastmeans).

bias_adjust

Adjust the back-transformed means (non-identity link or trans) to be means on the response scale: TRUE gives E\,h(\eta + u), u \sim N(0, \sigma^2), the mean over the random effects (and, for a transformed response of a linear model, the residual error), computed by Gauss-Hermite quadrature: \exp(\eta + \sigma^2/2) for a log, \eta^2 + \sigma^2 for a square root. "taylor" gives the second-order approximation h(\eta) + \sigma^2 h''(\eta)/2 (emmeans' bias.adjust), which is too low for a log when \sigma is large and off for a logit. The response-scale SEs follow by the delta method. FALSE (the default): the back-transformed mean is that of a unit with all random effects zero, or the median for a transformed response.

sigma

With bias_adjust = TRUE: the SD to adjust for. The default is the square root of the summed random-intercept variances (glmer, glmmTMB, lme), plus the residual variance for a transformed response of a linear (mixed) model; models with random slopes need it given.

average

How means average over the other factors when they are back-transformed: "link" (the default; average on the link scale, then back-transform) or "response" (back-transform each cell of the reference grid, then average with the same weights, as emmeans' regrid(): the mean of the response, e.g. a mean count). Both change only the response columns of means; the printed tables and the pairs stay on the link scale.

mean_type

Only for glmmTMB fits with zero inflation (ziformula); for other models the two are the same and the argument is ignored. "conditional" (default): the means of the count part, \mu. "overall": the overall means (1 - \pi)\mu (\pi the probability of an extra zero), with SEs from the joint covariance of the conditional and zero-inflation coefficients (delta method), averaged over the cells of the grid as average = "response" does; estimate is their log and the pairs are their ratios. Equal to glmmTMB's predict(type = "response") and to emmeans with component = "response". For log-link count families (poisson, nbinom1, nbinom2, ...).

Value

Predicted Means

A table of predicted means.

Standard Error of Means

A table of standard errors of predicted means.

Standard Error of Differences

Standard errors of differences between predicted means.

LSD

Least significant differences between predicted means (maximum, minimum and average), with the critical value that goes with adj (see there); attribute "Note" says when they are adjusted, or why not.

Pairwise p-value

Only when the pairs are displayed (see pairwise): a matrix with t values above the diagonal and p-values (adjusted by adj) below it; with atvar one matrix per level of atvar, named by the level.

mean_table

The means with SE, df and confidence limits (and letters when pairs are compared); for back-transformed means also the response-scale means and limits.

p_valueMatrix

Only when the pairs are displayed: the p-value matrix of the letters.

means

A data frame with one row per predicted mean and fixed column names: the factor (and covariate) columns, over (only when some mean averages over empty cells: the cells it averages, e.g. "N 0, 0.2, 0.4"; NA for the means over all their cells), estimate, std.error, df, conf.low, conf.high (confidence limits of each mean, not for comparing means), comparison.low and comparison.high (comparison intervals: two means differ at 1 - conf_level, with the adjustment of adj when it has a critical value, when these do not overlap; see letter_ci; present when the pairs are tabulated; NA for a mean over empty cells whose pairs are not the differences of the shown means (compared on common cells, or not estimable), which no interval around it can show); when the means are back-transformed also response, response.std.error (delta method, as emmeans with type = "response"), response.conf.low and response.conf.high; group (letters, when pairwise comparisons are made), n (number of observations) and estimable. Values are not rounded. Also returned by tidy() and as.data.frame().

pairs

A data frame with one row per pairwise comparison (NULL with one mean, or with more than 100 means when no comparison was asked for; see pairwise): level1, level2, by (the level of atvar, when given; NA for pairs across levels), estimate (mean of level1 minus mean of level2), std.error, df, statistic (t), p.value, p.adj (adjusted by adj, within each level of atvar when given), p.equiv (with equivalence: the TOST p-value), conf.low and conf.high (limits of each difference at conf_level, not adjusted), lsd (the half-width of those limits), adj.conf.low and adj.conf.high (simultaneous limits within each family, which exclude 0 exactly when p.adj is below 1 - conf_level, as SAS AdjLower and AdjUpper and emmeans; for adj "tukey" (each pair's own df, as SAS ADJDFE=ROW), "bonferroni", "sidak", "scheffe" and "mvt"; the step-down and false discovery rate methods have none) and p.method; with permlist the limits are permutation-t limits (estimate +- c SE, c the critical value of the permutation test), and the adjusted limits use the permutation distribution of the family's largest |t| ("tukey", "mvt", "westfall") or each pair's at level/m ("bonferroni", "sidak"); for a log link or trans = exp also ratio (of the back-transformed means, exp(estimate)), ratio.conf.low and ratio.conf.high, and for a logit link odds.ratio with its limits.

settings

A list with the options used: model term, significance level, adjustment method, atvar, degrees-of-freedom method, vcov_adjust, vcov ("model", "HC3", ...), singular (a singular lmer/glmer fit; a message says so too), number of permutations, covariate values, model class and package version; comparison, the comparison intervals: the multiplier mult of the SE, its confidence level, the number of pairs and how many of them are judged differently by their own tests, from the means shown (disagree; 0 and exact = TRUE when all SEDs are equal), and left_out, the means over empty cells that have none.

The result has class c("predictmeans", "pdmlist"). Printing shows the legacy tables; the means, pairs and settings elements are not printed. Plots come from autoplot(); notes for this fit are in attr(, "advice"), read with advice.

Covariates aliased with a factor

A covariate that takes one value within each level of a factor (a site mean, a block-level measurement) is aliased with that factor: in lm(ht ~ site + sitemean * seedlot) the coefficient of sitemean is NA. A mean over sites is then estimable only if each site keeps its own value of the covariate; at a single value, such as the overall mean, the "means" depend on the coding of the factors (which level is the reference) and are not estimates. predictmeans finds such covariates and uses each level's own value, with a message. predictmeans 1.x, and Genstat PREDICT after the covariate is dropped as aliased, used the overall mean; SAS LSMEANS reports such means as non-estimable. For a seedlot measured at every site the equal-weight mean is then its raw mean; for one with missing sites, weights = "equal" extrapolates its regression line to the missing sites and weights = "cells" averages over the sites it was measured at. See DataExam5.2.

Zero inflation (glmmTMB)

For a glmmTMB fit with zero inflation (ziformula) the means are those of the conditional (count) part, \mu, as emmeans and predict(type = "conditional") give, not the overall mean (1 - \pi)\mu (\pi the probability of an extra zero); ratios are of these means, and equal the ratios of overall means only when \pi is the same. A message says so and settings$component is "conditional". The two can order treatments differently when \pi differs between them. predictmeans(mean_type = "overall") gives the overall means and their ratios.

Note

The predictmeans function becomes confused if a factor or covariate is changed to the other in a model formula. Consequently, formulae that include calls as.factor, factor, or numeric (e.g. as.factor(income)) will cause errors. Instead, create the modified variables outside of the model formula (e.g., fincome <- as.factor(income)) and then use them in the model formula.

Factors cannot have colons in level names (e.g., "level:A") for the legacy tables; the predictmeans function will confuse the colons with interactions; rename levels to avoid colons. The means and pairs tables are not affected.

For predictmeans function, it is assumed that methods coef, vcov, model.matrix, model.frame and terms are available for model.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Torsten Hothorn, Frank Bretz and Peter Westfall (2008), Simultaneous Inference in General Parametric Models. Biometrical, Journal 50(3), 346–363.

Gilmour, A. R., Thompson, R. and Cullis, B. R. (1995), Average information REML: an efficient algorithm for variance parameter estimation in linear mixed models, Biometrics, 51(4), 1440-1450.

Welham, S., Cullis, B., Gogel, B., Gilmour, A., & Thompson, R. (2004), Prediction in linear mixed models, Australian and New Zealand Journal of Statistics, 46(3), 325-347.

Vanessa, C. (05 October 2022), Confidence tricks: the 83.4% confidence interval for comparing means, https://vsni.co.uk/blogs/confidence_trick.

Maghsoodloo, S. and Huang, C.-Y. (2010), Comparing the overlapping of two independent confidence intervals with a single confidence interval for two normal population parameters, Journal of Statistical Planning and Inference, 140(11), 3295-3305.

Goldstein, H. and Healy, M. J. R. (1995), The graphical presentation of a collection of means, Journal of the Royal Statistical Society A, 158(1), 175-177.

Austin, P. C. and Hux, J. E. (2002), A brief note on overlapping confidence intervals, Journal of Vascular Surgery, 36(1), 194-195.

Afshartous, D. and Preston, R. A. (2010), Confidence intervals for dependent data: equating non-overlap with statistical significance, Computational Statistics and Data Analysis, 54(10), 2296-2305.

See Also

autoplot.predictmeans, tidy.predictmeans, advice, pm_check, contrastmeans, pm_joint, covariatemeans

Examples

  library(predictmeans)
  Oats$nitro <- factor(Oats$nitro)
  fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data=Oats)
  ## The results as tables (columns described under Value)
  pm <- predictmeans(fm, "nitro")
  pm$means
  pm$pairs
  pm$settings
  summary(pm)
  ## Means within each variety, Tukey-adjusted pairs; plots from the result
  predictout <- predictmeans(fm, "nitro:Variety", atvar="Variety", adj="tukey")
  names(predictout)
  ggplot2::autoplot(predictout)                   # means, one LSD bar per variety
  ggplot2::autoplot(predictout, type = "bar")
  ## lme fits work the same way
  fl <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)
  predictmeans(fl, "nitro", adj="BH")$pairs

Functions removed in predictmeans 2.0

Description

These functions were removed in 2.0. Each stops with what to use instead; vignette("migrating") shows the 1.1.1 code beside the 2.0 code.

Removed Use
smZ(), smoothZ = smooths in the formula of semireg or semireg_tmb, e.g. smoothZ = list(sm = smZ(x)) is s(x, bs = "os")
permglmer(), permglmmTMB() permlmer() (they were the same function)
ci_mcp() predictmeans(..., letter_ci = TRUE): letters from comparison intervals, whose overlap agrees with the pairwise tests (overlap of confidence intervals does not)
R2_glmm() R2_model(model): the same values, as numbers
permanova.lmer() permmodels(model, type = ): Freedman-Lane permutations, so the p-values differ from the refits of permanova.lmer()

Arguments

...

Not used.


Diagnostic Plots for a Fitted Model

Description

Four diagnostic plots, drawn with ggplot2, for any model that predictmeans handles: lm, aov (also with Error() strata), glm, gls, lme, lmer, glmer, glmmTMB, mgcv::gam, semireg fits, and other classes with fitted() and residuals() methods. With interactive = TRUE they are shown with plotly: hovering a point gives its row of the data.

Usage

residplot(model, group = "none", re_level = 1, slope = FALSE, id = 3,
    interactive = FALSE, plot = TRUE, dense = c("auto", "points", "bins"), ...)

Arguments

model

A fitted model (see Description).

group

Optional variable that colours the points: the name (in "quotes") of a variable in the data of the model, or a vector with one value per observation. The default "none" uses one colour. The plots have no legend; interactive = TRUE shows each point's row and group on hover, and the plots can be given one with + ggplot2::theme(legend.position = "right").

re_level

For mixed models (level before 2.0): which random-effect term the random-effect plot shows, 1, 2, ... (in the order of ranef(): for lme the outermost grouping first, for lmer the innermost first).

slope

For mixed models: TRUE plots the random slopes (the second column of the random effects) instead of the random intercepts.

id

Number of the most extreme points labelled with their row names in the data (rows left out for missing values keep their numbers, so a label is the row to look at; largest absolute residuals; for the Cook's distance plot the largest distances); FALSE or 0 labels none. In 1.x id = TRUE let you click on points; now TRUE labels 3 points, and interactive = TRUE shows every point's row name.

...

Not used: level, newwd, ask (before 2.0) stop with their 2.0 spelling.

interactive

TRUE: show the plots with plotly (plotly::ggplotly()), which must be installed.

plot

FALSE: do not draw; only return the plots.

dense

How overlapping points are drawn. "points" (also "auto", the default): every point; beyond 200 points as open circles, more transparent as their number grows, so dense regions show darker and no point is hidden. "bins": the scatter plots as shaded counts in a grid of bins (darker: more points; no colour bar), with the points that stand out (the id largest and those beyond 3 on the residual scale) drawn on top. The Q-Q plot of more than 2000 residuals draws every point in the tails (outside the central 95%) and an even selection of the others.

Details

The plots:

  1. Residuals against fitted values, with a loess smooth (with fewer than 7 distinct fitted values, the mean residual at each, joined): look for trends (a missing term, a wrong link) and for spread that changes with the fitted values.

  2. Normal Q-Q plot of the residuals: the points should lie near the line.

  3. Mixed models: normal Q-Q plot of the random effects of term re_level. gls: autocorrelation of the normalized residuals (with approximate 95% limits). Other models: square root of the absolute residuals against fitted values (scale-location), for spread that changes with the fitted values.

  4. lm, aov and glm: Cook's distances. Other models (also gam: Cook's distances of a penalized fit are only approximate): fitted against observed values of the response as modelled (from pm_data: the rows used in the fit; the axis is labelled with the response as written, e.g. log(yield + 1), or the observed proportion for cbind(successes, failures)); for a 0/1 response (also a two-level factor), the observed proportion against the mean fitted probability in tenths of the fitted values (calibration).

Residuals: standardized for lm (rstandard()), normalized for gls and lme (the correlation structure removed), scaled by the residual standard deviation for lmer. For Poisson, binomial and negative binomial models (glm, glmer, glmmTMB, gam) randomized quantile residuals (Dunn and Smyth, 1996): exactly normal when the model is right, so plots 1 and 2 are read as for a normal model (they use a fixed random seed, so the plots do not change between calls); fitted values are then on the link scale. Other families: standardized deviance residuals. aov with Error(): the residuals of the lowest stratum. The plots inform; they do not test. For a table of checks see pm_check; for Cook's distances of mixed models CookD.

Value

Invisibly, a list of the four ggplot objects (class "pm_residplot"), with attribute "data": the data frame of the points (row label, fitted, residual, observed values, group). With interactive = TRUE, the plotly widget.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Dunn, P. K. and Smyth, G. K. (1996), Randomized quantile residuals, Journal of Computational and Graphical Statistics, 5, 236-244.

See Also

pm_check, CookD

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)
residplot(fm, re_level = 2)    # lme: re_level = 2 for random effect "Block:Variety"

fm <- lmer(yield ~ nitro*Variety+(1|Block/Variety), data=Oats)
residplot(fm, group = "Variety") # lmer: re_level = 1 for random effect "Block:Variety"

# a Poisson GLM: randomized quantile residuals
gm <- glm(breaks ~ wool * tension, family = poisson, data = warpbreaks)
p <- residplot(gm, plot = FALSE)
p[[2]]                               # one of the plots
# interactive plots (hover for each point's row)
if (interactive() && requireNamespace("plotly", quietly = TRUE)) residplot(fm, interactive = TRUE)

Scallop Abundance off Long Island

Description

Scallop catches at 148 locations of a 1990 survey cruise on the Atlantic continental shelf off Long Island, New York (Ecker and Heltshe 1994; the data of HRW::scallop), with the knots of M. P. Wand's thin-plate spline fit (scallopKnots) and the boundary of the survey area (scallopBdry).

Usage

data(scallop)
data(scallopKnots)
data(scallopBdry)

Format

scallop: a data frame with 148 rows and 3 columns:

latitude

degrees latitude (north).

longitude

degrees longitude (negative: west).

tot.catch

total scallop catch at the location.

scallopKnots (37 rows) and scallopBdry (77 rows, a polygon): data frames with columns longitude and latitude.

Source

Ecker, M. D. and Heltshe, J. F. (1994). Geostatistical estimates of scallop abundance. In Case Studies in Biometry, eds. N. Lange et al., Wiley, New York, 107-124.

References

Ruppert, D., Wand, M. P. and Carroll, R. J. (2003). Semiparametric Regression. Cambridge University Press.

Examples

data(scallop)
data(scallopKnots)
data(scallopBdry)
# a thin-plate surface of asinh(catch) (low-rank kriging) with the given knots
fit <- semireg(asinh(tot.catch) ~ s(longitude, latitude, bs = "ztps",
                                   xt = list(knots = as.matrix(scallopKnots))),
               data = scallop)
anova(fit)$smooth
# the surface inside the survey area, on the scale of the catch
semipred(fit, covariate = c("longitude", "latitude"), boundary = scallopBdry, trans = sinh)$plt

Standard Errors of the Predicted Random Effects

Description

The predicted random effects (BLUPs, conditional modes) of a mixed model with their standard errors and limits, and optionally the predicted value of each level (fixed part plus random effect).

Two standard errors are available:

type = "prediction"

(the default) the prediction error SE, \sqrt{Var(\hat u - u)}, from the inverse of the mixed model equations (Henderson's C_{22}; SAS PROC MIXED RANDOM / SOLUTION, "Std Err Pred"). It includes the uncertainty of the estimated fixed effects, which matters most for a term that contains a fixed factor (e.g. Block:Variety with Variety fixed).

type = "conditional"

the conditional SE, \sqrt{Var(u \mid y)} with the fixed effects treated as known: lme4's ranef(condVar = TRUE), the numbers of se_ranef() in predictmeans 1.x. It is smaller.

Both treat the variance parameters as known (the usual plug-in), except for glmmTMB: there "conditional" is ranef(condVar = TRUE) of glmmTMB, which is TMB's sdreport() and includes the uncertainty of the fixed effects and of the variance parameters (so it can exceed "prediction", which inverts the (\beta, b) block of TMB's joint precision, variance parameters known). Correlated terms, nested and crossed terms, glmmTMB structures (us, cs, ar1, ...) and lme correlation and variance structures are all covered, as the SEs come from the joint covariance of all random effects. For GLMMs, all values are on the link scale.

With predict = TRUE, each level gets its predicted value: for a random term with no fixed factor in it (Block), the overall mean (the fixed factors averaged with equal weights, as predictmeans; covariates at their means) plus \hat u; for a term that contains fixed factors (Block:Variety, Variety fixed), the predicted mean of that fixed level plus \hat u. Its SE is from the joint covariance of (\hat\beta, \hat u - u), L C L' with L = [k', e_i] ("prediction" always). Only intercept rows get a prediction (random slopes: NA). For GLMMs the response scale is added by the inverse link (SE by the delta method).

Usage

se_ranef(
  object,
  rand_term = NULL,
  type = c("prediction", "conditional"),
  predict = FALSE,
  conf_level = 0.95
)

## S3 method for class 'pm_ranef'
print(x, n = 10, digits = 4, ...)

Arguments

object

An lmer, glmer, glmmTMB (conditional model), lme or semireg fit.

rand_term

Optional name of one grouping factor, e.g. "Block" or "Variety:Block" (lme: the level name, e.g. "Variety" for ~ 1 | Block/Variety).

type

"prediction" (default) or "conditional" (1.x); see Description.

predict

Add the predicted value of each level (see Description)?

conf_level

Confidence level of the limits.

x

A pm_ranef result.

n

Rows printed per group.

digits

Digits printed.

...

Not used.

Value

A data frame of class pm_ranef: group, level, term, estimate (the BLUP), std.error, conf.low, conf.high (normal limits \hat u \pm z\,SE: for "prediction" a prediction interval of u); with predict = TRUE also prediction, prediction.std.error, prediction.conf.low, prediction.conf.high, and for GLMMs response, response.std.error, response.conf.low, response.conf.high. attr(, "settings") records type, conf_level, limits, model_class, scale and conditional (what the conditional SE is for this class). as.list() gives the 1.x result: one matrix of SEs (levels x terms) per group, or that matrix only when rand_term was given.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Henderson, C. R. (1975). Best linear unbiased estimation and prediction under a selection model. Biometrics, 31, 423-447.

See Also

varcomp, residplot, advice

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
se_ranef(fm, "Block")
se_ranef(fm, "Block", type = "conditional")     # 1.x numbers
se_ranef(fm, "Variety:Block", predict = TRUE)   # cell values
as.list(se_ranef(fm, type = "conditional"))     # 1.x list of matrices

Boundary of the region covered by two-dimensional data

Description

Draws a boundary around the points of two covariates (such as longitude and latitude, or the coordinates of drill holes), following the shape of the data, for the boundary option of semipred: predictions of a surface are then shown only where the data support them, not in the empty corners of the rectangle the grid covers.

Usage

semiboundary(
  x,
  y = NULL,
  mult = 2,
  d = NULL,
  buffer = 0.5,
  scale = c("auto", "lonlat", "same", "sd"),
  min_hole = 20,
  n = 150
)

Arguments

x

A matrix or data frame with two columns (the two covariates, e.g. longitude and latitude), or a numeric vector with y.

y

A numeric vector, when x is one.

mult

The closing distance d as a multiple of the 95th percentile of the nearest-neighbour distances (default 2).

d

The closing distance itself (on the scale of scale), instead of mult.

buffer

The margin left around the outer points, as a multiple of the median nearest-neighbour distance (default 0.5).

scale

How the two covariates are put on comparable scales: "auto" (default), "lonlat", "same" or "sd" (see Details).

min_hole

Holes smaller than the area of this many data points (the region's area divided by the number of points, times min_hole; default 20) are filled: the empty patches that random sampling leaves, not areas without data. 0 keeps every hole.

n

The least number of grid cells along the longer side of the data the outline is traced on (default 150); finer where the data are dense (cells of at most d / 4, up to a million cells).

Details

The region is the morphological closing of the data with a distance d. First every place within d of a data point is taken (a union of discs), which follows any concave shape; then that region is shrunk back by d less a small buffer, so that the boundary keeps close to the outer points instead of bulging by d beyond them. Gaps narrower than about 2 d inside the data are filled; larger empty areas stay outside (holes), and clusters further apart than that become separate pieces. The outline is traced on a grid of n by n points with contourLines (base R: no other package is needed).

d follows the density of the data: by default mult = 2 times the 95th percentile of the distances from each point to its nearest neighbour. A high percentile, not the median, because randomly placed points leave empty patches several times the typical spacing: with twice the median, uniform random designs of 50 to 1000 points gave on average 4 pieces and 12 spurious holes; with the default, one piece and no holes (every point inside), while a real empty area (points on a ring) stays a hole. On the scallop survey the default boundary covers 85% of the same area as the boundary drawn with the original analysis (scallopBdry; intersection over union), with every point inside.

Distances need the two covariates on comparable scales (scale): "lonlat", longitude and latitude in degrees, longitude shrunk by the cosine of the mean latitude (a degree east is shorter than a degree north away from the equator); "same", coordinates in the same unit (metres, a local grid), used as they are; "sd", two different variables, each divided by its standard deviation. "auto" (default) takes "lonlat" when the columns are named like longitude and latitude (in that order) with values in range, else "sd".

Value

A data frame with the two columns of x (same names), the vertices of the boundary's rings in order, rings separated by a row of NA (as polygon draws them); a point is inside when it is inside an odd number of rings. Attributes d (the closing distance) and scale.

Suggestions

See Also

semipred (boundary = TRUE uses this function on the model's data), the data sets scallop and copper.

Examples

library(predictmeans)
## 1. The scallop survey (longitude and latitude): the boundary from the data (blue) and the
##    boundary drawn with the original analysis (red)
data(scallop); data(scallopBdry)
b <- semiboundary(scallop[, c("longitude", "latitude")])
attr(b, "scale")                                   # "lonlat", from the column names
plot(latitude ~ longitude, data = scallop, asp = 1/cos(40*pi/180), pch = 16, cex = 0.6,
     xlim = range(b$longitude, na.rm = TRUE), ylim = range(b$latitude, na.rm = TRUE))
polygon(b, border = "blue", lwd = 2)
polygon(scallopBdry, border = "red", lwd = 2)
legend("bottomright", c("semiboundary()", "scallopBdry"), col = c("blue", "red"),
       lwd = 2, bty = "n")

## 2. Copper drill holes (coordinates in the same unit): how 'mult' changes the region;
##    with mult = 1 the hole far to the left is a separate piece
data(copper)
holes <- unique(copper[, c("xcoord", "ycoord")])
b1 <- semiboundary(holes, mult = 1, scale = "same")
b2 <- semiboundary(holes, scale = "same")
b4 <- semiboundary(holes, mult = 4, scale = "same")
plot(holes, asp = 1, pch = 16, xlim = range(b4$xcoord, na.rm = TRUE),
     ylim = range(b4$ycoord, na.rm = TRUE))
polygon(b1, border = "orange", lwd = 2)
polygon(b2, border = "blue", lwd = 2)
polygon(b4, border = "darkgreen", lwd = 2)
legend("topleft", c("mult = 1", "mult = 2 (default)", "mult = 4"),
       col = c("orange", "blue", "darkgreen"), lwd = 2, bty = "n")

## 3. Pieces and holes: random points on a ring (the empty middle is a hole) and a separate
##    cluster; polypath() shades the region with the hole left open
set.seed(1)
th <- runif(400, 0, 2*pi); r <- runif(400, 2, 3)
pts <- data.frame(x = c(r*cos(th), runif(80, -3, -2)), y = c(r*sin(th), runif(80, 3.5, 4.5)))
br <- semiboundary(pts)
plot(pts, asp = 1, pch = 16, cex = 0.4)
polypath(br, col = adjustcolor("skyblue", 0.4), border = "blue", lwd = 2, rule = "evenodd")
sum(is.na(br$x)) + 1                               # 3 rings: the ring's two edges and the cluster


## Surfaces shown only inside the boundary, with its outline and the data
library(ggplot2)
outline <- function(b) { b$ring <- cumsum(is.na(b[[1]])); b }
data(scallopKnots)
fs <- semireg(asinh(tot.catch) ~ s(longitude, latitude, bs = "ztps",
                                  xt = list(knots = as.matrix(scallopKnots))), data = scallop)
semipred(fs, covariate = c("longitude", "latitude"), boundary = b, trans = sinh)$plt +
  geom_path(data = outline(b), aes(longitude, latitude, group = ring), inherit.aes = FALSE,
            na.rm = TRUE)

data(copperKnots)
fc <- semireg(grade ~ s(xcoord, ycoord, bs = "ztps", xt = list(knots = as.matrix(copperKnots))) +
                s(zcoord, bs = "os"), data = copper)
semipred(fc, covariate = c("xcoord", "ycoord"), boundary = b2)$plt +
  geom_path(data = outline(b2), aes(xcoord, ycoord, group = ring),
            inherit.aes = FALSE, na.rm = TRUE) +
  geom_point(data = holes, aes(xcoord, ycoord), inherit.aes = FALSE, size = 0.8)
# boundary = TRUE draws the boundary from the model's data (scale "auto": here "sd")
semipred(fc, covariate = c("xcoord", "ycoord"), boundary = TRUE)$plt


Predicted Curves and Surfaces of a Semiparametric Model

Description

Predicted curves (or surfaces) of a semiparametric model along a covariate, with pointwise or simultaneous bands; their slopes (deriv), or the difference between two curves (contr). The result holds the tables in the layout of predictmeans (see tidy.pm_curves) and the plot, which autoplot() returns.

Usage

semipred(model, modelterm=NULL, covariate, sm_term=NULL, contr=NULL, at=NULL,
         boundary=NULL, conf_level=0.95, trans=NULL, contr_scale=c("model", "response"),
         band=c("pointwise", "simultaneous"),
         unconditional=getOption("predictmeans.semi_unconditional"), deriv=0,
         plot_args=list(), mean_type=c("conditional", "overall"),
         bias_adjust=FALSE, sigma=NULL, plot=getOption("predictmeans.plot", FALSE), ...)

Arguments

model

A fit of semireg or semireg_tmb (semireg before 2.0).

modelterm

Name (in "quotes") of the factor term whose curves are predicted, as in the model formula, e.g. "A" or "A:B" (any number of factors: every combination is computed; autoplot(x, group = , panel = ) chooses the layout). With NULL or the name of the covariate, one curve without grouping. Factors that are not in modelterm, including by factors of the smooth terms, are averaged over with equal weights, in both the parametric and the smooth parts of the model.

covariate

Name (in "quotes") of the covariate, or two names for a surface, e.g. c("x1", "x2").

sm_term

The smooths used in the prediction; the default NULL uses all of them. print(model) (or tidy(model)) lists the smooths of the fit with the values to use here. Each entry may be a term as written in the formula ("s(pressure, by = QB)", all its pieces), a smooth as labelled ("s(pressure):QB200", column smooth), a covariate ("pressure": every smooth of it, column covariate) or a random-effect term ("s_pressure_QB200", column term). Smooths of other covariates enter the curves as a constant; the advice smooth_other_covariate says when the prediction includes such smooths. settings$sm_term records the blocks used.

contr

Two levels of modelterm (numbers or names, e.g. c(4, 1) or c("d", "a")): the difference of their curves (level 4 minus level 1), with limits, along covariate.

at

The values of covariate to predict at (covariateV before 2.0): a numeric vector (one covariate) or a matrix with one named column per covariate (two covariates, e.g. for a Ztps smooth); each row of the matrix is one prediction point.

boundary

For two covariates (a surface): the region where predictions are shown. A matrix or data frame of two columns (the covariates in the order of covariate), the vertices of a polygon, or of several rings separated by a row of NA (a point is inside when it is inside an odd number of them: separate pieces and holes), such as semiboundary() returns; or TRUE for semiboundary() of the model's data (the region the data cover, following their shape). NULL (default): the whole grid.

conf_level

Confidence level of the two-sided limits, default 0.95 (level = 0.05 before 2.0; before 2.0 the limits used qnorm(1 - level), i.e. 90%). For gaussian fits the limits are t limits with Satterthwaite df at each point (column df; see Details); for generalized fits t limits with the df of the design's strata (inner-outer, as for GLMMs), normal limits when the model has no random term besides the smooths.

trans

A function that back-transforms the curves, e.g. trans = exp. Without it the curves are back-transformed by the inverse link of a generalized fit, or by the inverse of a response transformed in the formula (log(y), sqrt(y), log(y + 1), ...), as in covariatemeans (one rule for both); trans = I keeps the model scale.

bias_adjust, sigma

For back-transformed curves, as in covariatemeans: by default a curve is the back-transformed fitted value (the median for a transformed response, a typical cluster for a GLMM); bias_adjust = TRUE gives the mean of the response, over the residual variance (transformed response) and the variances of the random intercepts other than the smooths (the smooths' random effects are the curves themselves), or sigma^2.

mean_type

Only for glmmTMB fits with zero inflation (ziformula; ignored, with a message, for other models): "conditional" (default), curves of the means of the count part, \mu; "overall", curves of the overall means (1 - \pi)\mu (\pi the probability of an extra zero), their bands \exp(\log m \mp crit\,SE) with the SE of \log m from the joint covariance of the count and zero-inflation coefficients (delta method), and with contr the ratio and the difference of the overall means. Log-link count families only.

plot_args

Superseded by the arguments of autoplot.pm_curves, kept for 1.x scripts (before 2.0 arguments of their own; given so they stop with this spelling). A named list: trellis (TRUE, default: one panel per level), scales ("fixed", default, "free", "free_x", "free_y": the axes of the panels), plotord (the order of the two factors of a two-way term, e.g. c(2, 1); giving it draws the plot), ci (draw the bands, TRUE), point (draw the data, TRUE), jitterv (jitter of the points, 0), threeD (a 3-D surface with plotly, FALSE); and colours and sizes, any of: line and band (one curve; dark and light blue), diff_line and diff_band (a difference of two curves, contr; dark and light green), ref (the dashed reference line at 0, or 1 for ratios, and the marks under a difference where its band leaves out the reference; red), alpha (of the bands, 0.35), linewidth (1), points, point_alpha, point_size (the data: grey, 0.6, 1.3), palette (curves by group: eight colours that colour-blind readers can tell apart; ggplot2's own beyond eight groups), surface_points (the data on surfaces: red). Bands are drawn first and their lines on top. For example plot_args = list(line = "black", band = "grey70"); the plot is a ggplot, so anything else can be added to it.

plot

Draw the plot now? The default is FALSE (since 2.0; 1.x drew it): the plot is in the result (autoplot() returns it). plot = TRUE, or options(predictmeans.plot = TRUE) for a whole session, draws it; so does plot_args = list(plotord = ).

...

Not used: arguments removed in 2.0 (semireg, covariateV, level, prt, simultaneous, the plot settings) stop with their 2.0 spelling (see vignette("migrating")).

band

"pointwise" (the default) or "simultaneous": simultaneous confidence bands over the whole curve(s) instead of pointwise limits; the critical value is the 1 - level quantile of the largest standardised deviation over the predicted points, from 10000 draws of the estimates' distribution (Ruppert, Wand and Carroll, 2003); for gaussian fits a multivariate t with the df of each point (Details). The same argument as in covariatemeans, where lines of a parametric model use Scheffe's critical value instead; for smooths that would be far too wide.

unconditional

If TRUE, the covariance of the coefficients includes the uncertainty of the smoothing parameters (the variances of the smooth terms), as mgcv's unconditional = TRUE: the first-order correction J V_\theta J' is added, J the derivative of the estimated coefficients in the variance parameters and V_\theta the covariance of their estimates (from the Hessian of the deviance; for semireg_tmb() fits TMB's joint precision of all parameters). The default (NULL) is TRUE for generalized models and FALSE for gaussian ones: in a simulation of the difference between two curves (dev/sim-curve-difference.R, 150 data sets, nominal 0.95) the bands without it covered 0.93 pointwise and 0.89-0.91 over the whole curve for Poisson and binary data, and 0.955-0.957 and 0.94-0.95 with it; for gaussian data 0.97 without it (0.98 with it). options(predictmeans.semi_unconditional = TRUE) (or FALSE) sets it for semipred() and predictmeans() on semireg fits.

deriv

0 (the default): the curves; 1: their slopes, 2: their curvatures (first and second derivatives along covariate, one covariate), with bands as for the curves, and with contr the difference of the slopes (curvatures) of two curves. See ‘Slopes and curvature’.

contr_scale

With contr and a generalized model: "model" (the default) plots the difference on the link scale, as the ratio (log link) or the odds ratio (logit link) of the two curves; "response" the difference of the back-transformed curves with a delta-method band. See ‘Comparing two lines’ in covariatemeans: the test is on the model scale.

Details

Degrees of freedom (gaussian fits, both engines): a point of a curve, or of a difference of curves, is a combination of fixed and smooth (random) coefficients. Its df are Satterthwaite's for that combination (as predictmeans on the fit and SAS for estimates that involve random effects), counting the variance components of the design (blocks, plots, ...) and the residual; the smoothing parameters are held at their estimates (their uncertainty is what unconditional adds), and components estimated at zero are left out. So the df are the residual df when there is no other random term, and few where a design stratum dominates (curves of treatments applied to whole plots). Pointwise limits use qt(1 - level/2, df) at each point. Simultaneous bands use a multivariate t: the simulated deviations are divided by variance estimates that move together over the points (each point with its own df), the points are put on one scale by their t probabilities, and each point gets the t quantile of its df at the simulated 1 - level quantile (with one df for all points: the exact multivariate t).

Generalized fits (both engines) take the df that predictmeans gives GLMMs: the inner-outer df of the stratum of the design's random effects in which the fixed coefficients of a point vary (a curve of a treatment applied to whole plots: the whole-plot df), the smooth blocks left out (they are not strata of the design); with no random term besides the smooths, normal limits (as for a glm with a known dispersion). In a simulation (‘dev/sim-semireg-glmm-df.R’; Poisson counts in the split plot above, 1000 data sets per setting) normal limits rejected 5.8-9.2% of true equalities of two treatments at a time and covered a treatment's curve 0.91-0.93, the t limits (10 df) 3.1-5.9% and 0.955-0.970; bands of differences covered 0.92-0.96 (normal) and 0.95-0.996 (t).

In a simulation (‘dev/sim-semipred-df.R’; split plot, 6 blocks, 3 treatments on whole plots, curves over 11 times; 500 data sets per setting) normal limits of a treatment's curve covered 0.91 pointwise and 0.92 over the whole curve, these t limits (about 8-11 df) 0.94-0.95 and 0.96-0.97; for differences of curves (15-31 df) normal 0.94-0.96, t 0.96-0.97. With curves by group and no design strata both covered 0.95-0.98.

With contr the difference between two curves is computed as in covariatemeans, from the contrast of the two curves and the covariance of the fixed and smooth coefficients. For a linear model pred_df has the difference (in the column of the response), LL, UL, SE_contr and the indicators includes0 (the limits include zero) and significant. For a generalized model it has the columns of covariatemeans(contr = ): diff, ses, LL, UL and includes0 on the link scale; the ratio or odds.ratio with its limits and ..includes1; response.diff, response.ses, response.LL, response.UL and response.includes0 on the response scale; and significant (the link scale). Before 2.0 the band of a generalized model's difference used the standard error of the link-scale difference multiplied by a weight evaluated at the difference of the means, which is not a standard error of any difference. The same difference is in the table pairs in the layout of predictmeans(). The ranges of the covariate where the curves differ are printed with the result and kept in significant and attr(pred_df, "significant"); with band = "simultaneous" they hold for the whole curve, and the curves differ somewhere at level 1 - conf_level when there is such a range. (A joint F test, as covariatemeans() gives, is not given: Wald tests of penalised smooth coefficients are not reliable.)

Value

An object of class c("semipred", "pm_curves"), a list. tidy() and as.data.frame() return its table, autoplot() the plot, and print() shows a summary (see tidy.pm_curves); notes in attr(, "advice") (advice).

means

The curves: the factor columns of modelterm, the covariate(s), estimate, std.error, df, conf.low, conf.high on the model scale (pointwise limits), with a simultaneous band adj.conf.low, adj.conf.high; for generalized fits and with trans also response, response.std.error, response.conf.low, response.conf.high (and response.adj.conf.*). NULL with contr or deriv.

slopes

With deriv = 1 (2): the slopes (curvatures) in the same columns, with statistic, p.value and, with a simultaneous band, p.adj.

pairs

With contr: the difference of the two curves, as covariatemeans()$pairs; with a simultaneous band p.adj is the share of the simulated maxima at least as large (below 0.05 exactly where the band leaves out zero; the smallest value is 1/10000).

settings

The options: df_method, band, deriv, unconditional, back_transform, ...; with contr, test: whether the curves differ anywhere along the covariate, the max-|t| test (statistic the largest |t| over the points, p.value the share of simulated maxima at least as large, from the covariance of the fixed and smooth coefficients: the smallest level at which the simultaneous band leaves out zero somewhere). A Wald F test of the smooth coefficients is not used: they are shrunken, and the statistic would not have an F distribution. In a simulation of equal curves (200 data sets) it rejected 3.0% at the 5% level.

significant

With contr or deriv: the ranges of the covariate where the band asked for leaves out zero.

plt

autoplot() of the result with plot_args: a ggplot (one plotly widget for threeD); drawn only when plot = TRUE.

pred_df

The 1.x table: a data.frame with the predicted values, their limits LL and UL (the band asked for), SE and df; for generalized fits the means and limits are on the response scale (limits h(eta -+ crit SE)), SE on the link scale and SE_mu on the response scale (delta method), df when the limits are t; with contr the columns described in Details.

Slopes and curvature

With deriv = 1 (2) each row of the prediction design is replaced by its first (second) derivative along the covariate, by central differences of the whole design (the fixed part and every smooth basis, on the same grid), so the slopes are those of the fitted curves for any basis; for the O'Sullivan basis (bs = "os", 1.x smZ()) they equal the exact derivatives of the basis (ZOSull(drv = )), to 1e-8. Standard errors, df and pointwise or simultaneous bands are computed as for the curves; generalized models give the slopes of the linear predictor (link scale). pred_df holds the slopes in the column of the response, with includes0 and significant; the ranges of the covariate where the band lies above or below zero (the curve rises or falls) are printed with the result and kept in attr(pred_df, "significant"). A covariate scaled by semireg(nscale = TRUE) is differentiated in its own units. The table slopes of the result has the slopes with statistic and p.value of slope = 0 (and p.adj with a simultaneous band), and significant the ranges. In a simulation (‘dev/sim-semipred-deriv.R’; y = \sin(x/1.5) plus noise, 150 points, 500 data sets) the bands covered the true slope 0.97 pointwise and over the whole range with the default 6 knots, 0.99-1.00 with 15; the curvature 0.98-1.00.

Zero inflation (glmmTMB)

For a glmmTMB fit with zero inflation (ziformula) the means are those of the conditional (count) part, \mu, as emmeans and predict(type = "conditional") give, not the overall mean (1 - \pi)\mu (\pi the probability of an extra zero); ratios are of these means, and equal the ratios of overall means only when \pi is the same. A message says so and settings$component is "conditional". The two can order treatments differently when \pi differs between them. mean_type = "overall" (predictmeans(), covariatemeans(), semipred()) gives the overall means and their ratios.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Ruppert, D., Wand, M. P. and Carroll, R. J. (2003), Semiparametric Regression, Cambridge University Press.

See Also

semireg, tidy.pm_curves, semiboundary, covariatemeans, advice

Examples

library(predictmeans)
data(Dialyzer, package = "nlme")
library(ggplot2)
ggplot(Dialyzer, aes(x = pressure, y = rate, col = QB)) +
  geom_line() +
  facet_wrap(vars(Subject))

# a curve per blood flow rate, a random intercept and slope per dialyzer
fm <- semireg(rate ~ s(pressure, by = QB, bs = "os", k = 4) + (pressure | Subject),
              data = Dialyzer)
residplot(fm$semer, group = "QB")
anova(fm)   # fixed effects (Kenward-Roger) and a test of each smooth term

# the curves with pointwise bands (t limits with Satterthwaite df), then simultaneous ones
out <- semipred(fm, "QB", "pressure")
out
autoplot(out)

autoplot(semipred(fm, "QB", "pressure", band = "simultaneous"), panel = character(0))
# the smooths of one term only, as written in the formula
semipred(fm, "QB", "pressure", sm_term = "s(pressure, by = QB)")$settings$sm_term
# at given pressures
semipred(fm, "QB", "pressure", at = c(0.5, 1, 1.5, 2))

# the difference of the two curves, and where they differ
dif <- semipred(fm, "QB", "pressure", contr = c("300", "200"), band = "simultaneous")
dif$significant
head(as.data.frame(dif))

# slopes of the curves, and where they differ from zero over the whole range
slp <- semipred(fm, "QB", "pressure", deriv = 1, band = "simultaneous")
slp$significant

# a surface: copper grade over the plane and a smooth in depth (data(copper))
data(copper)
fcu <- semireg(log(grade) ~ s(zcoord, bs = "os") + s(xcoord, ycoord, bs = "ztps", k = 6),
               data = copper)
autoplot(semipred(fcu, covariate = "zcoord", trans = exp))
autoplot(semipred(fcu, covariate = c("xcoord", "ycoord"), trans = exp))

# a binary response: the probability scale, and the odds ratio of two curves
set.seed(4)
db <- expand.grid(x = seq(0, 1, length = 25), g = factor(c("a", "b")), cl = factor(1:12))
db$y <- rbinom(nrow(db), 1, plogis(-1 + 2*sin(pi*db$x) + 0.8*(db$g == "b")*db$x +
                                     rnorm(12, 0, 0.5)[db$cl]))
fbin <- semireg(y ~ s(x, by = g, bs = "os", k = 6) + (1 | cl), family = binomial, data = db)
autoplot(semipred(fbin, "g", "x"))
head(as.data.frame(semipred(fbin, "g", "x", contr = c("b", "a"))))


Semiparametric Mixed Models Fitted with lme4

Description

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.

Usage

semireg(formula, data, family = NULL, REML = TRUE,
        control = lmerControl(optimizer = "nloptwrap"),
        start = NULL, verbose = FALSE, drop_unused_levels = TRUE, subset, weights,
        offset, contrasts = NULL, ...)

Arguments

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 family); NULL (the default) is gaussian.

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 lmerControl(optimizer = "nloptwrap") ("bobyqa" in 1.x), also used for generalized fits.

start

Starting values, as for lmer or glmer.

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 contrasts.arg of model.matrix.default.

...

Further arguments for passing on to model setup routines. Arguments removed in 2.0 (smoothZ, ncenter, nscale, resp_scale, prt, predict_info, ngbinomial) stop with their 2.0 spelling; nothing is printed during the fit (print(fit$semer)). For a negative binomial model use semireg_tmb(family = glmmTMB::nbinom2): the 1.x ngbinomial = TRUE estimated theta from a Poisson fit, which is not the maximum-likelihood fit.

Details

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.

Value

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. 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 lmer or glmer model (class semerMod for gaussian fits).

call

The call of semireg().

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. s(x, by = f)).

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 semipred() and predictmeans()).

Smooth terms in the formula

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 x (x1 + x2)
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 linearly dependent columns or columns in the span of its fixed part; a warning says when it fails just beyond the ends of the data (the slopes of semipred(deriv = ) there need it). Its values are checked again at prediction.

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) since 2.0: on these examples it reached the same optimum as bobyqa (1.x's default; control = lmerControl(optimizer = "bobyqa")) faster, also for binomial and Poisson fits. 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.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

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.

See Also

semireg_tmb, anova.semireg, semipred, varcomp, predictmeans

Examples

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
}


Semiparametric Mixed Models Fitted with glmmTMB

Description

Fit a semiparametric (additive mixed) model with glmmTMB: smooth terms written in the formula, as in mgcv::gam, are fitted as random effects, next to glmmTMB's families (e.g. negative binomial), zero inflation, dispersion models and covariance structures. smZ()/smoothZ of 1.x are superseded (removed in 2.0); see vignette("migrating").

Usage

semireg_tmb(formula, data, family = gaussian(), ziformula = ~0,
        dispformula = ~1, weights = NULL, offset = NULL, contrasts = NULL, na.action,
        se = TRUE, verbose = FALSE, doFit = TRUE, control = glmmTMBControl(),
        REML = TRUE, start = NULL, map = NULL, sparseX = NULL, ...)

Arguments

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

data frame (tibbles are OK) containing model variables. Not required, but strongly recommended; if data is not specified, downstream methods such as prediction with new data (predict(fitted_model, newdata = ...)) will fail. If it is necessary to call glmmTMB with model variables taken from the environment rather than from a data frame, specifying data=NULL will suppress the warning message.

family

a family function, a character string naming a family function, or the result of a call to a family function (variance/link function) information. See family for a generic discussion of families or family_glmmTMB for details of glmmTMB-specific families.

ziformula

a one-sided (i.e., no response variable) formula for zero-inflation combining fixed and random effects: the default ~0 specifies no zero-inflation. Specifying ~. sets the zero-inflation formula identical to the right-hand side of formula (i.e., the conditional effects formula); terms can also be added or subtracted. When using ~. as the zero-inflation formula in models where the conditional effects formula contains an offset term, the offset term will automatically be dropped. The zero-inflation model uses a logit link.

dispformula

a one-sided formula for dispersion containing only fixed effects: the default ~1 specifies the standard dispersion given any family. The argument is ignored for families that do not have a dispersion parameter. For an explanation of the dispersion parameter for each family, see sigma. The dispersion model uses a log link. In Gaussian mixed models, dispformula=~0 fixes the residual variance to be 0 (actually a small non-zero value), forcing variance into the random effects. The precise value can be controlled via control=glmmTMBControl(zero_dispval=...); the default value is sqrt(.Machine$double.eps).

weights

weights, as in glm. Not automatically scaled to have sum 1.

offset

offset for conditional model (only).

contrasts

an optional list, e.g., list(fac1="contr.sum"). See the contrasts.arg of model.matrix.default.

na.action

a function that specifies how to handle observations containing NAs. The default action (na.omit, inherited from the 'factory fresh' value of getOption("na.action")) strips any observations with any missing values in any variables. Using na.action = na.exclude will similarly drop observations with missing values while fitting the model, but will fill in NA values for the predicted and residual values for cases that were excluded during the fitting process because of missingness.

se

whether to return standard errors.

verbose

whether progress indication should be printed to the console.

doFit

whether to fit the full model, or (if FALSE) return the preprocessed data and parameter objects, without fitting the model.

control

control parameters, see glmmTMBControl.

REML

whether to use REML estimation rather than maximum likelihood. Gaussian fits use REML by default; for other families the default is maximum likelihood (Laplace), as glmer, unless REML = TRUE is given. (Before 2.0 the default never reached glmmTMB, so gaussian fits were maximum likelihood.)

start

starting values, expressed as a list with possible components beta, betazi, betad (fixed-effect parameters for conditional, zero-inflation, dispersion models); b, bzi (conditional modes for conditional and zero-inflation models); theta, thetazi (random-effect parameters, on the standard deviation/Cholesky scale, for conditional and z-i models); psi (extra family parameters, e.g., shape for Tweedie models).

map

a list specifying which parameter values should be fixed to a constant value rather than estimated. map should be a named list containing factors corresponding to a subset of the internal parameter names (see start parameter). Distinct factor values are fitted as separate parameter values, NA values are held fixed: e.g., map=list(beta=factor(c(1,2,3,NA))) would fit the first three fixed-effect parameters of the conditional model and fix the fourth parameter to its starting value. In general, users will probably want to use start to specify non-default starting values for fixed parameters. See MakeADFun for more details.

sparseX

a named logical vector containing (possibly) elements named "cond", "zi", "disp" to indicate whether fixed-effect model matrices for particular model components should be generated as sparse matrices, e.g. c(cond=TRUE). Default is all FALSE

...

Not used: arguments removed in 2.0 (smoothZ, prt, predict_info) stop with their 2.0 spelling; nothing is printed during the fit (print(fit$semer)).

Details

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.

Value

A list of class semireg, as for semireg: print() shows the formula, the smooth terms (with the smooth, term and covariate values that semipred takes for sm_term and covariate), the fixed effects, other variance components and any advice; summary(), tidy() and the extractors (coef(), vcov(), VarCorr(), ...) are those described there. Notes on the fit are in attr(, "advice") (advice). Its elements:

semer

The fitted glmmTMB model.

call

The call of semireg_tmb().

data

A data.frame with generated variables in the fitting.

fomul_vars

Name of variables in the formula of semireg_tmb 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. s(x, by = f)).

df

Degree of freedom of all random terms.

tmbf

The glmmTMB model result using doFit=FALSE.

Correlation structures

glmmTMB's covariance structures can be written next to the smooths and are kept as written: ar1(), ou() (unequally spaced times, with glmmTMB::numFactor()), cs(), toep(), diag(), and the spatial exp(), gau(), mat(). Residuals correlated in time within subjects are written as ar1(time_factor + 0 | subject) with dispformula = ~0 (the structure is then the residual covariance; with a residual variance as well it is AR1 plus a nugget, and cs() plus a residual variance is not identified), e.g. semireg_tmb(y ~ s(time, by = trt) + ar1(tf + 0 | id), dispformula = ~0, data = d). semireg() (lme4) has no such structures and refuses them.

Smooth terms in the formula

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(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)) 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)) x1 + x2
s(x, bs = "user", xt = list(basis = f)) a basis of your own (see semireg) x
t2(x1, x2) tensor-product surface, a variance per penalty 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. 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), as in semireg (te() is fitted as t2(); ti() is not available).

Zero inflation (glmmTMB)

For a glmmTMB fit with zero inflation (ziformula) the means are those of the conditional (count) part, \mu, as emmeans and predict(type = "conditional") give, not the overall mean (1 - \pi)\mu (\pi the probability of an extra zero); ratios are of these means, and equal the ratios of overall means only when \pi is the same. A message says so and settings$component is "conditional". The two can order treatments differently when \pi differs between them. mean_type = "overall" (predictmeans(), covariatemeans(), semipred()) gives the overall means and their ratios.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

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.

See Also

semireg, anova.semireg, semipred, varcomp

Examples

library(predictmeans)
## Counts with extra zeros: curves of two treatments, a random site effect, a negative
## binomial with zero inflation; the rate ratio of the curves along x and where it differs
## from 1
set.seed(5)
cn <- expand.grid(x = seq(0, 3, length = 30), trt = factor(c("ctl", "trt")), site = factor(1:8))
cn$y <- rnbinom(nrow(cn), size = 3,
                mu = exp(1 + sin(cn$x) + (cn$trt == "trt")*0.5*cn$x + rnorm(8, 0, 0.3)[cn$site]))
cn$y[runif(nrow(cn)) < 0.1] <- 0
fc <- semireg_tmb(y ~ s(x, by = trt, bs = "os", k = 6) + (1 | site), ziformula = ~ 1,
                  family = glmmTMB::nbinom2, data = cn)
rr <- semipred(fc, "trt", "x", contr = c("trt", "ctl"), band = "simultaneous")
attr(rr$pred_df, "significant")
predictmeans(fc, "trt", covariate = c(x = 1.5))$means

## Repeated measures: curves over time, AR(1) correlation within subjects (the residual
## covariance, dispformula = ~0); means at a time with Satterthwaite df
set.seed(7)
d <- expand.grid(t = 1:8, id = factor(1:12))
d$A <- factor(rep(c("a1", "a2", "a3"), each = 32))
d$y <- sin(d$t/3) + rnorm(12, 0, 0.4)[d$id] +
  unlist(lapply(1:12, function(i) as.numeric(stats::arima.sim(list(ar = 0.6), 8, sd = 0.4))))
d$tf <- factor(d$t)
fa <- semireg_tmb(y ~ s(t, by = A, bs = "os", k = 4) + (1 | id) + ar1(tf + 0 | id),
                  dispformula = ~0, data = d)
predictmeans(fa, "A", covariate = c(t = 4), pairwise = TRUE)$pairs
varcomp(fa)

## Binary responses with a random intercept per child (HRW::indonRespir)
if (requireNamespace("HRW", quietly = TRUE)) {
  data(indonRespir, package = "HRW")
  fb <- semireg_tmb(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
}


Contrasts Written with Level Names

Description

Build a contrast matrix for contrastmeans by writing each contrast as an expression in the level names of a model term, so there is no need to count columns, even when some treatment combinations are missing. Each level name (in backticks when it is not a syntactic name, e.g. `Wet:Bio`) stands for that mean.

Usage

specify_contrast(.x, ..., .zero_sum = TRUE)

Arguments

.x

A result of Kmatrix or predictmeans for the term, or a character vector of its level names (as in the row names of Kmatrix(model, modelterm)$K).

...

Named expressions, one per contrast, e.g. Bio_vs_None = (`Wet:Bio` + `Dry:Bio`)/2 - (`Wet:None` + `Dry:None`)/2.

.zero_sum

If TRUE (the default), every contrast's weights must sum to zero. Use FALSE for other linear combinations of the means, such as the average of two means.

Details

The arguments start with a dot so that contrasts can be given any name, including x.

Value

A matrix with one row per contrast (named as given) and one column per level. Columns of levels that are not mentioned are zero. Means that cannot be estimated (e.g. missing cells) cannot be used.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

contrastmeans, contrast_family, pm_joint

Examples

  library(predictmeans)
  Oats <- as.data.frame(nlme::Oats)
  Oats$nitro <- factor(Oats$nitro)
  fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
  cm <- specify_contrast(Kmatrix(fm, "nitro:Variety"),
    N_effect_Victory = `0.6:Victory` - `0:Victory`,
    N_effect_vs_others = (`0.6:Victory` - `0:Victory`) -
                         ((`0.6:Golden Rain` - `0:Golden Rain`) +
                          (`0.6:Marvellous` - `0:Marvellous`))/2)
  contrastmeans(fm, "nitro:Variety", ctrmatrix = cm)

Curves and Their Differences as Data Frames

Description

The results of covariatemeans and semipred hold their tables in the layout of predictmeans: means (one row per point of a curve or surface), slopes (semipred(deriv = )) and, with contr, pairs (the difference of two curves at each covariate value), with the same column names (estimate, std.error, df, conf.low, conf.high, ...) and the covariates under their own names. tidy() and as.data.frame() return them, autoplot.pm_curves draws them and print() shows a short summary.

Usage

## S3 method for class 'pm_curves'
tidy(x, what = c("means", "pairs", "slopes"), ...)

## S3 method for class 'pm_curves'
as.data.frame(x, row.names = NULL, optional = FALSE,
              what = c("means", "pairs", "slopes"), ...)

## S3 method for class 'pm_curves'
print(x, n = 10, digits = 4, ...)

Arguments

x

A result of covariatemeans or semipred.

what

Which table: "means", "pairs" or "slopes". The default is the one the result has ("pairs" for a result with contr, "slopes" for semipred(deriv = 1)).

row.names

Optional row names for the result.

optional

Not used.

n

The number of rows printed.

digits

Significant digits printed.

...

Not used.

Value

tidy() and as.data.frame(): a data frame with unrounded values. In every table conf.low and conf.high are pointwise limits (t with the row's df); with band = "simultaneous" the simultaneous band is in adj.conf.low and adj.conf.high, with p.adj where there is a test (Scheffe over the covariate values for covariatemeans(), the simulated maximum for semipred(); the adjusted p-value is below level exactly where the band leaves out zero, up to the resolution of the 10000 draws for semipred()). Columns beginning response are the same quantities on the response scale (back-transformed limits for means, delta-method limits for differences).

means

The factor columns of modelterm, the covariate(s), estimate, std.error, df, conf.low, conf.high (the model scale: the link, or the transformed response) and, when the curves are back-transformed, response, response.std.error (delta method), response.conf.low, response.conf.high.

slopes

(semipred(deriv = 1, 2)) The same columns for the slopes (curvatures) on the model scale, with statistic (t) and p.value of slope = 0.

pairs

level1, level2, the covariate(s), estimate (level1 minus level2 on the model scale), std.error, df, statistic (t), p.value, conf.low, conf.high; ratio or odds.ratio with their (pointwise) limits for a log or logit scale; and response, response.std.error, response.conf.low, response.conf.high, the difference of the back-transformed curves.

settings (a list in the result) records modelterm, covariate, level, contrast, band, df_method, vcov_adjust, vcov, back_transform, test (covariatemeans(): the joint F test that the two curves are the same, with the columns of pm_joint: df1, df2, F.ratio, p.value), for semipred() also deriv, unconditional and boundary, then component (zero-inflated glmmTMB fits), model_class and version. significant (in the result) holds the ranges of the covariate where the band asked for leaves out zero.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

covariatemeans, semipred

Examples

  library(predictmeans)
  data(Oats, package="nlme")
  fm <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)
  cm <- covariatemeans(fm, "Variety", covariate="nitro", at=c(0, 0.3, 0.6))
  cm
  as.data.frame(cm)
  cd <- covariatemeans(fm, "Variety", covariate="nitro", contr=c("Golden Rain", "Victory"),
                       band="simultaneous")
  head(as.data.frame(cd))
  if (requireNamespace("ggplot2", quietly = TRUE)) ggplot2::autoplot(cd)

Predicted Means and Pairwise Comparisons as Data Frames

Description

Return the means or pairs table of a predictmeans result (glance(): one row describing it). The tables have fixed column names (see the Value section of predictmeans) and unrounded values, which makes them easy to use in further analysis, reports, Shiny apps or AI tools. tidy() is the generic from package generics (also used by broom); as.data.frame() needs no other package. coef() and vcov() return the means (on the model scale, as in the estimate column) and their covariance matrix (Kenward-Roger adjusted when the means are), named by the mean labels. With them, multcomp::glht() or marginaleffects::hypotheses() can test any contrast of the means, e.g. hypotheses(pm, hypothesis = "n2 - n0 = 0") (normal-based). Recent versions of marginaleffects need the class listed first: options(marginaleffects_model_classes = "predictmeans").

Usage

## S3 method for class 'predictmeans'
tidy(x, what = c("means", "pairs"), ...)

## S3 method for class 'predictmeans'
glance(x, ...)

## S3 method for class 'predictmeans'
as.data.frame(x, row.names = NULL, optional = FALSE,
              what = c("means", "pairs"), ...)

## S3 method for class 'predictmeans'
coef(object, ...)

## S3 method for class 'predictmeans'
vcov(object, ...)

Arguments

x

A result of predictmeans.

object

A result of predictmeans.

what

Which table: "means" (the default) or "pairs".

row.names

Optional row names for the result.

optional

Not used.

...

Not used.

Value

A data frame; for coef() a named vector and for vcov() a matrix. glance() gives one row: modelterm, n.means, n.pairs, nobs (observations in the cells), df.method, adjust, level, vcov, vcov.adjust, sed.min, sed.mean, sed.max (standard errors of the differences), lsd.mean, nperm and model.class.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

See Also

predictmeans, autoplot.predictmeans, advice

Examples

  library(predictmeans)
  Oats <- as.data.frame(nlme::Oats)
  Oats$nitro <- factor(Oats$nitro)
  fm <- lmer(yield ~ nitro*Variety + (1|Block/Variety), data = Oats)
  pm <- predictmeans(fm, "nitro:Variety", atvar = "Variety", adj = "tukey")
  as.data.frame(pm)
  head(as.data.frame(pm, what = "pairs"))
  if (requireNamespace("generics", quietly = TRUE)) generics::glance(pm)

  # Any contrast of the means from coef() and vcov(): Victory - Golden Rain at nitro 0.6
  b <- coef(pm)
  L <- (names(b) == "0.6:Victory") - (names(b) == "0.6:Golden Rain")
  c(estimate = sum(L*b), SE = sqrt(drop(L %*% vcov(pm) %*% L)))

Variance Components with Standard Errors and Confidence Intervals

Description

The variance components of a fitted model, with standard errors and confidence intervals, for every model class that predictmeans handles: the random-effect variances and covariances and the residual variance of lmer, lme and glmmTMB models (also with correlation and variance structures and random slopes), the random-effect (co)variances of glmer models, the correlation and variance-function parameters of gls and lme models, the stratum variance components of aov models with Error(), the smoothing variance components of mgcv::gam models and semireg fits, and the error term of lm, aov and glm models (residual variance, dispersion, or the negative binomial \theta).

Usage

varcomp(model, ci = TRUE, conf_level = 0.95,
        ci_method = c("Satterthwaite", "Wald", "profile"),
        information = c("observed", "average", "expected"), test = FALSE,
        test_method = c("auto", "mixture", "bootstrap"), nsim = 10000, nboot = 999,
        ncore = 1, ...)

Arguments

model

A fitted model (see Description).

ci

TRUE (the default): add confidence intervals.

conf_level

Confidence level of the intervals; the default is 0.95 (level before 2.0).

...

Not used: level (before 2.0) stops with its 2.0 spelling.

ci_method

How the intervals of variances are made: "Satterthwaite" (the default) chi-square intervals with \nu = 2 (estimate/SE)^2 df, as SAS PROC MIXED (COVTEST CL); "Wald" Wald intervals on the log scale; "profile" (lmer, glmer) lme4's profile-likelihood intervals, which for a REML fit are those of the ML fit (lme4 profiles the ML deviance), so they do not go with the REML estimates. The other components always get the Wald intervals of the Details.

information

For REML fits of lmer, lme and gls models: the information matrix of the variance parameters behind the SEs: "observed" (the default, as SAS PROC MIXED), "average" (the average information of Genstat's and ASReml's REML: Genstat's s.e.) or "expected"; the same choices as for the Kenward-Roger df (df_method of predictmeans). Other fits use the observed information.

test

TRUE: add a likelihood ratio test of each component being zero (lmer, glmer, glmmTMB and semireg fits; see ‘Tests’). The default is FALSE: each test refits the model once.

test_method

"auto" (the default) or "mixture": the reference distribution of a single variance (see ‘Tests’); "bootstrap": a parametric bootstrap of each likelihood ratio, for small samples, few levels, or where the asymptotic references are conservative.

nsim

Number of draws of the exact null distribution of the restricted likelihood ratio (default 10000, with a fixed seed, so the p-values repeat).

nboot

Maximum number of bootstrap samples per test (default 999); a test stops early once 20 simulated statistics reach the observed one.

ncore

Number of cores for the bootstrap (default 1; a socket cluster on Windows). The p-values are the same for any ncore.

Details

Standard errors are from the observed information of the variance parameters (the inverse Hessian of the REML, or ML, deviance at the estimates, as SAS PROC MIXED and the Kenward-Roger df of predictmeans), carried to the variance components by the delta method: lmer from the deviance in (theta, sigma), glmer from the Hessian lme4 stores for (theta, beta) (nAGQ = 0 fits: the deviance in theta), lme and gls from the REML (ML) log-likelihood in their unconstrained modelStruct parameters (any pdMat, corStruct and varFunc), glmmTMB from vcov(full = TRUE).

Intervals of variances: Satterthwaite's chi-square interval [\nu \hat\sigma^2/\chi^2_{\nu, 1-\alpha/2}, \nu \hat\sigma^2/\chi^2_{\nu, \alpha/2}] with \nu = 2 (\hat\sigma^2/SE)^2 (positive and skewed as the sampling distribution of a variance; for the residual variance of an lm it is the exact interval, \nu the residual df; for the stratum components of an aov Satterthwaite's interval from the mean squares). Other components: Wald intervals on the scale where the parameter is unbounded: atanh for correlations (a covariance: the interval of its correlation times the two SDs), log for other positive parameters (varIdent ratios, ranges, \theta), and the natural scale otherwise (e.g. the power of varPower). A variance estimated at its bound, zero, has no SE (the interval is (0, NA)), as SAS prints it; an analysis of variance estimate can be negative.

lm, aov, gaussian glm: the residual variance s^2 with SE s^2 \sqrt{2/df} and the exact chi-square interval. Other glm families with an estimated dispersion (Gamma, inverse gaussian, quasi): the Pearson dispersion, with the same (approximate) SE and interval. Poisson and binomial: the dispersion is fixed at 1 (no SE). Negative binomial (MASS::glm.nb): \theta with its SE.

aov with Error(): the analysis of variance (method of moments) estimates of the variance of each error stratum, from the stratum mean squares and their expectations (as Genstat's stratum variances; they equal the REML estimates in balanced designs when positive, and can be negative), with SEs from var(MS) = 2 MS^2/df and Satterthwaite's chi-square intervals; with missing values, those of the design completed as in predictmeans.

gam: mgcv::gam.vcomp() (variances of the smooths, and the scale), its intervals squared, and the SEs from their width on the log scale; it needs method = "REML" or "ML".

Value

A data frame with one row per component (random-effect variances and covariances by group, named group.term and group.term1.term2; correlation and variance-function parameters named cor.name and var.name; residual) and columns vcov (the estimate), SE and, with ci = TRUE, the limits. Values are rounded to 4 decimals; attribute "ci_method" says how the intervals were made. With test = TRUE also LRT and p.value, and class "pm_varcomp" (printed with the hypotheses). Notes on this fit (e.g. a variance estimated at zero, few levels) are kept in attr(, "advice"); read them with advice.

Tests

With test = TRUE each row gets the likelihood ratio test of the model one would fit without it (columns LRT and p.value; the hypotheses and reference distributions are printed below the table and kept in attr(, "tests")):

Row Model refitted Reference distribution
variance of a one-variance term (1 | g), smooth block the term dropped \frac12\chi^2_0 + \frac12\chi^2_1; exact restricted LRT when it is the only random effect of a gaussian lmer/semireg REML fit
slope variance in (1 + x | g) (k components) (1 | g) \frac12\chi^2_{k-1} + \frac12\chi^2_k
intercept variance of (1 + x | g), variance of ar1() etc. the whole term dropped \chi^2 with the term's number of parameters (conservative)
covariance in (1 + x | g) (1 + x || g) (glmmTMB: diag()) \chi^2 with the number of covariances
correlation of ar1(), ou(), cs() homdiag() / diag() \chi^2_1
residual variance; a structure that is the residual covariance (dispformula = ~0) no test

A variance is on the boundary of its range under the hypothesis, so its likelihood ratio has the mixture distributions of Self and Liang (1987) and Stram and Lee (1994), not \chi^2_1 (which is conservative, as lmerTest::ranova()). When the tested variance is the only random effect of a gaussian model fitted by REML, the exact finite-sample null distribution of Crainiceanu and Ruppert (2004) is used (simulated); with other random effects present that distribution is no longer exact (in simulations it was too liberal), and the mixture is used. The mixture p-values equal SAS PROC GLIMMIX COVTEST, the likelihood ratios SAS PROC MIXED and Genstat REML (tests/testthat/test-vc-test.R). Where a p-value may be inaccurate in either direction (a term with fewer than 6 levels; binary data with fewer than 5 observations per level, where the Laplace approximation is poor), a warning names the rows and suggests the bootstrap.

test_method = "bootstrap": for each test, responses are simulated from the model without the component (new random effects and errors), both models are refitted to each, and the p-value is (\#\{LRT^* \ge LRT\} + 1)/(b + 1). It needs no distributional approximation, so it is the check for the rows the warning names. A test stops once 20 simulated statistics reach the observed one (Besag and Clifford 1991): a clearly non-significant row needs some 40-400 refits, a significant one all nboot pairs. Each draw has its own seed, so the p-values repeat, with or without ncore. Run time: a few seconds to a minute for usual lmer and glmer models; glmmTMB fits are slower (each refit rebuilds the model). For lme, gls, gam and models without random effects test = TRUE is not available.

Which method: in a simulation of seven designs (‘dev/sim-vc-defaults.R’ in the package sources) the default rejected at most 4.5% of the data sets without the component at the 5% level: it was never liberal. For GLMMs it was conservative (binary data in clusters of four 0.5%, Poisson 4%, negative binomial 0%), and there the bootstrap rejected 1.5-6% and found 5-7% more of the real components. Use the default for gaussian models and as a quick first look; use the bootstrap for GLMMs, small data sets, the rows a warning names, and a p-value near the cut-off.

Author(s)

Dongwen Luo, Siva Ganesh and John Koolaard

References

Besag, J. and Clifford, P. (1991). Sequential Monte Carlo p-values. Biometrika, 78, 301-304.

Crainiceanu, C. M. and Ruppert, D. (2004). Likelihood ratio tests in linear mixed models with one variance component. Journal of the Royal Statistical Society B, 66, 165-185.

Self, S. G. and Liang, K.-Y. (1987). Asymptotic properties of maximum likelihood estimators and likelihood ratio tests under nonstandard conditions. Journal of the American Statistical Association, 82, 605-610.

Stram, D. O. and Lee, J. W. (1994). Variance components testing in the longitudinal mixed effects model. Biometrics, 50, 1171-1177.

See Also

anova.semireg, R2_model, se_ranef, advice

Examples

library(predictmeans)
Oats$nitro <- factor(Oats$nitro)
fm <- lmer(yield ~ nitro*Variety+(1|Block/Variety), data=Oats)
varcomp(fm)
# is each variance needed? (one refit per row)
varcomp(fm, test = TRUE)

# the same by parametric bootstrap (a few seconds; more draws and ncore for real use)
varcomp(fm, test = TRUE, test_method = "bootstrap", nboot = 99)

# a GLMM: the boundary mixture is conservative here, the bootstrap nearer 5%
gm <- glmer(cbind(incidence, size - incidence) ~ period + (1 | herd),
            family = binomial, data = lme4::cbpp)
varcomp(gm, test = TRUE)
fm1 <- lme(yield ~ nitro*Variety, random=~1|Block/Variety, data=Oats)
varcomp(fm1)
# the same components by the analysis of variance
varcomp(aov(yield ~ nitro*Variety + Error(Block/Variety), data=Oats))

data(Orthodont, package="nlme")
mod1 <- lme(distance ~ age, random=~age|Subject, data=Orthodont)
varcomp(mod1)
# correlation and variance structures
mod2 <- gls(distance ~ age*Sex, correlation=corAR1(form=~1|Subject),
            weights=varIdent(form=~1|Sex), data=Orthodont)
varcomp(mod2)
# the error term of a linear model
varcomp(lm(yield ~ Block + nitro*Variety, data=Oats))

Trade Union Membership and Wages

Description

Hourly wage and trade union membership of 534 workers (the Current Population Survey of 1985, Berndt 1991), the data of M. P. Wand's penalised spline logistic regression example.

Usage

data(wageTUnion)

Format

A data frame with 534 rows and 2 columns:

wage

hourly wage (US dollars).

unionMember

1 for a union member, 0 otherwise.

Source

Berndt, E. R. (1991). The Practice of Econometrics: Classic and Contemporary. Addison-Wesley.

References

Ruppert, D., Wand, M. P. and Carroll, R. J. (2003). Semiparametric Regression. Cambridge University Press.

Examples

data(wageTUnion)
# the probability of union membership as a smooth function of the wage
fit <- semireg(unionMember ~ s(wage, bs = "os", k = 15), family = binomial, data = wageTUnion)
anova(fit)$smooth
semipred(fit, "wage", "wage")$plt