| 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
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
What predictmeans aims for
Defaults chosen on evidence (simulation, literature): Kenward-Roger df and adjusted SEs for REML
lmerfits; permutation p-values(b + 1)/(B + 1), never 0; Genstat-style stratum SEs foraovmodels withError()strata.Checked against outside references: SAS PROC MIXED and Genstat runs (
dev/sas,dev/genstatin the package sources), pbkrtest, nlme and emmeans, in tests with stated tolerances.Works across
lm,glm,aov,lmer,glmer,lme,gls,glmmTMB,gamandsemiregfits; when a result cannot be computed correctly it stops with a clear message.Advice triggered by this fit and data, read with
advice.Results are the same for any
ncore.
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,
FemaleorMale.- Habitat
factor,
AorB.- Treatment
factor,
ContorExp.- 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
readscrandmathscr).- 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,
controlordrug.- 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 |
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 |
plot |
|
id |
The number of the largest Cook's distances labelled in the plot ( |
... |
Not used: |
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
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
htat 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: |
modelterm |
Name (in "quotes") of the variables whose combinations give the rows of |
covariate |
The values of covariates; those not mentioned are at their means (see
For a |
at |
Values for the covariate(s) named in |
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 ( |
cov_reduce |
How covariates that are not varied are handled. A function returning a single value, applied to each covariate
(the default |
exclude |
For |
weights |
How the cells of the factors that are not in |
refgrid |
Return the grid of all combinations (element |
Value
K |
Coefficients matrix. It has an attribute |
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 |
|
empty_cells |
|
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. |
conf_level |
The p-values below |
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: |
values |
Whether to print each p-value on its tile (the default is
|
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,
Femaleonly.- Habitat
factor,
BorA.- Treatment
factor,
ExporCont.- 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 |
method |
|
over_disp |
For |
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
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 |
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 |
... |
Other fitted models: then lme4's comparison of the models. |
type |
|
ddf |
|
advice |
Logical: add a note on the choice of type when the data are unbalanced or have empty cells
(default |
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 |
type |
|
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 |
type |
|
group, panel |
Names of factors of |
scales |
The axes of the panels: |
scale |
|
data |
Draw the data ( |
jitter |
Jitter of the data points, in x and y (units of the axes). |
interval |
|
title |
The title; |
style |
Colours and sizes, any of: |
... |
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 |
type |
|
interval |
For |
scale |
|
scales |
For |
data |
Add the observations ( |
x, group, panel |
Names of factors of |
lines |
For |
jitter |
Horizontal jitter of the data points, in units of the x categories. |
values |
For |
digits |
Number of significant digits printed (plus two). |
... |
For |
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 |
nsim |
Number of simulated data sets, the default is 999. |
type |
The type of ANOVA table (as in |
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: |
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; useadj = "mvt"incontrastmeansfor 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 |
family |
The family of contrasts (see Description). |
ref |
For |
by |
Optional name(s) of factor(s) of the term: build the family within each of their levels. |
max_degree |
For |
... |
Not used: |
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 |
modelterm |
Name (in "quotes") for indicating which factor term's contrast to be calculated.
The |
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 |
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 |
permlist |
A list from |
vcov_adjust |
For models fitted by REML ( |
weights |
Passed to |
df_method |
Denominator df, by method or as one number (a fixed df, |
joint |
Logical: also test all the contrasts together (all of them zero), as |
conf_level |
Confidence level of the limits of the contrasts ( |
vcov |
Optional covariance of the coefficients to use instead of the model's. For |
equivalence |
Optional equivalence margins for equivalence tests (two one-sided t tests, TOST) of the
contrasts: a positive number |
... |
Not used: arguments removed in 2.0 ( |
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 |
K |
A contrast matrix. |
Joint F test of the contrasts |
With |
and then the tables in the layout of predictmeans, unrounded:
contrasts |
One row per contrast: |
joint |
With |
settings |
|
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 |
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 |
as_is |
|
at |
The values of |
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 ( |
trans |
A function object for calculating the back transformed means, e.g. |
plot_args |
Superseded by the arguments of |
... |
Not used: arguments removed in 2.0 ( |
cov_reduce |
How covariates that are not varied are handled when building the predicted means: a function such as
|
exclude |
For |
weights |
Passed to |
df_method, vcov_adjust |
As in |
contr |
Two levels of |
contr_scale |
With |
band |
With |
mean_type |
Only for |
plot |
Draw the plot now? The default is |
bias_adjust, sigma |
For back-transformed lines (a link, a transformed response or |
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 |
pairs |
With |
settings |
The options that produced them (df method, level, band, back-transformation, ...). |
plt |
|
pred_df |
( |
test, significant |
With |
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:
At one covariate value chosen beforehand: the pointwise band (
band = "pointwise"); the lines differ at the level1 - conf_levelwhen it leaves out zero (one for a ratio).Over which range of the covariate: looking at many values needs wider limits.
band = "simultaneous"uses Scheffe's critical valuec = \sqrt{r F_{1-\alpha;\,r,\,df}},rthe 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.Whether the lines differ anywhere: the joint F test that all the differences along the covariate are zero (
testin 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 |
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 |
ctrmatrix |
A contrast matrix on the fixed-effect coefficients (one column per coefficient of
|
ctrnames |
Names of the rows of |
df_method |
The method for the degrees of freedom (called |
... |
Arguments removed in 2.0 ( |
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 |
method |
How the p-values of the responses are combined: |
tests |
Names of the terms and coefficients ( |
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
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 |
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
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 |
|
model1 |
|
... |
Not used: |
nperm |
Number of permutations; default 999. |
ncore |
Number of cores (default 1; before predictmeans 2.0: 3). |
plot |
|
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 |
method |
For GLMMs only: |
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 |
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);
|
test_statistic |
The statistic of Type II and III tests with |
exact |
|
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: |
ncore |
Number of cores (default 1; before predictmeans 2.0: 3). Each permutation has its own seed, so
the results do not depend on |
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: |
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 |
refit |
For |
robust |
For |
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 |
conf_level |
The check of the parametric test is at the significance level |
... |
Not used: |
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
|
df1, df2 |
numerator and denominator df of the usual parametric test: the residual df for |
p.param |
the parametric p-value of the observed statistic with these df. |
p.perm |
the permutation p-value (as in the tables of |
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
|
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
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 |
lambda |
The power: one number. Box-Cox: 1 leaves the shape of |
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
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 |
plot |
|
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
residplotuses: 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 (CookDfor mixed models).- Normality
Shapiro-Wilk tests of the residuals and of each term's random effects (intercepts).
- Transformation of the response
(
lmandaovwith a positive response that is not transformed in the formula) the Box-Cox power the residuals favour: the profile likelihood estimate of\lambdaand its 95% interval (Box and Cox, 1964; asMASS::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.2and 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 |
Details
pm_coef(model)Named fixed-effect estimates, with
NAfor aliased coefficients. Default:coef(model); methods forlme,merModandglmmTMBreturn 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 inpm_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 storedpredvars, sopoly(),ns(),scale()etc. use the fitted basis), contrasts and factor levels. Thegammethod 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 thedataargument of the call,getData()or the model frame;Kmatrix()uses apm_data()method only when the class has its own.pm_df(model, L)Denominator degrees of freedom for each row of
L, orNULL(the default) to use the model's single residual df:df.residual(model), orInf(normal-based) when there is none. Kenward-Roger df forlmerand the rules of nlme forlmeare built in.pm_linkinv(model)Inverse link function used to back-transform the means, or
NULLfor none. Default: the inverse link offamily(model)unless it is the identity.pm_contrasts(model)The contrasts of the factors used in the fit, as for the
contrasts.argargument ofmodel.matrix(). Default: those ofmodel.matrix(model), elsemodel$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
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 |
... |
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 |
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 |
modelterm |
Name (in "quotes") of the model term whose means are compared, e.g. |
by |
Optional name(s) of factor(s) of |
ctrmatrix |
Optional contrast matrix over the means of |
df_method |
For |
weights |
How the means average over other factors, as in |
vcov |
Optional covariance of the coefficients, as in |
Details
The F statistic and its denominator degrees of freedom follow the model:
lmerKenward-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): aslmerTest::contest(joint = TRUE); containment: the Wald F with the containment df ofmodelterm.- KR-expected
(
lmer,lme,gls) Kenward-Roger with the expected information, aspbkrtest::KRmodcomp()(seepredictmeans).- 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 ofmodelterm(SASDDFM=BETWITHIN; seepredictmeans).lme,glswithdf_method = "Satterthwaite","Kenward-Roger","KR-expected"or"KR-average"as for
lmer(Satterthwaite df of the F test, lmerTest's rule).lme,glsKenward-Roger for REML fits and Satterthwaite for ML fits (the defaults), as for
lmer; withdf_method = "containment"the Wald F with nlme's df ofmodelterm(asanova();"containment (nlme)") or the residual df (gls).glmwith 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 |
covariate |
Name (in "quotes") of the numeric covariate. |
modelterm |
Name (in "quotes") of the factor term whose levels get a slope each, e.g. |
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 ( |
adj |
Adjustment of the p-values of the pairwise comparisons of slopes, as in |
df_method, vcov_adjust, weights, vcov |
As in |
... |
Not used: |
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 |
pairs |
one row per pair of levels: |
settings |
|
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 |
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 |
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: |
atvar |
Factor(s) of |
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 |
conf_level |
The confidence level of the confidence limits; the tests, LSDs and letters are at the
significance level |
covariate |
The values of covariates at which the means are predicted: a named list or vector, e.g.
|
meandecr |
Logical: order the letters of |
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
|
trans |
A function object for calculating the back transformed means, e.g. |
... |
Not used: arguments removed in 2.0 (e.g. |
permlist |
A list from |
ncore |
Number of cores for parallel computing when |
cov_reduce |
How covariates that are not varied are handled when building the predicted means: a function such as
|
exclude |
For |
vcov_adjust |
For models fitted by REML ( |
weights |
Passed to |
df_method |
Denominator degrees of freedom, by method or as one number (a fixed df, |
vcov |
Optional covariance of the coefficients to use instead of the model's. For |
equivalence |
Optional equivalence margins for equivalence tests (two one-sided t tests, TOST) of the
differences: a positive number |
bias_adjust |
Adjust the back-transformed means (non-identity link or |
sigma |
With |
average |
How means average over the other factors when they are back-transformed: |
mean_type |
Only for |
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 |
Pairwise p-value |
Only when the pairs are displayed (see |
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, |
pairs |
A data frame with one row per pairwise comparison ( |
settings |
A list with the options used: model term, significance level, adjustment method, |
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 |
re_level |
For mixed models ( |
slope |
For mixed models: |
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); |
... |
Not used: |
interactive |
|
plot |
|
dense |
How overlapping points are drawn. |
Details
The plots:
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.
Normal Q-Q plot of the residuals: the points should lie near the line.
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.-
lm,aovandglm: Cook's distances. Other models (alsogam: Cook's distances of a penalized fit are only approximate): fitted against observed values of the response as modelled (frompm_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 forcbind(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
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'sC_{22}; SAS PROC MIXEDRANDOM / 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:VarietywithVarietyfixed).type = "conditional"the conditional SE,
\sqrt{Var(u \mid y)}with the fixed effects treated as known: lme4'sranef(condVar = TRUE), the numbers ofse_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 |
rand_term |
Optional name of one grouping factor, e.g. |
type |
|
predict |
Add the predicted value of each level (see Description)? |
conf_level |
Confidence level of the limits. |
x |
A |
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
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 |
A numeric vector, when |
mult |
The closing distance |
d |
The closing distance itself (on the scale of |
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: |
min_hole |
Holes smaller than the area of this many data points (the region's area divided by the number of
points, times |
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 |
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
Look at the boundary with the data before using it (
plot()of the points andpolygon()of the boundary, as in the examples). It is a choice about where predictions are believable, not an estimate.-
mult: the default suits most designs, regular grids and random sampling alike. Use 3 or 4 for sparse or uneven sampling, or to keep one region where the data come in clusters; use 1 to 1.5 to follow the corners of a regular grid tightly. Separate pieces for clusters far apart are honest: there are no data between them. -
scale: for map coordinates in metres (UTM, a local grid) givescale = "same", so that the shape is not stretched; for two different covariates (for example temperature and pressure) the default"sd"keeps predictions to the combinations that were observed, which avoids extrapolating a surface into corners without data. The boundary only chooses which grid points
semipred()shows; it does not change the fit. Near the edge the bands are wider, as they should be.A boundary of your own (a coastline, a farm or field outline) can be given to
semipred()directly: two columns, several rings separated by a row ofNA.Holes:
semipred()leaves them out (a point is inside when it is inside an odd number of rings). To shade a region with holes usepolypath(b, rule = "evenodd"); to draw the outline with ggplot2 number the rings,b$ring <- cumsum(is.na(b[[1]])), and usegeom_path(aes(group = ring)), as in the examples.Large data: about 0.1 s for 150 points, 4 s for 10,000 and 9 s for 50,000; the grid the outline is traced on gets finer as the data get denser (up to a million cells).
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 |
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; |
covariate |
Name (in "quotes") of the covariate, or two names for a surface, e.g. |
sm_term |
The smooths used in the prediction; the default |
contr |
Two levels of |
at |
The values of |
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 |
conf_level |
Confidence level of the two-sided limits, default 0.95 ( |
trans |
A function that back-transforms the curves, e.g. |
bias_adjust, sigma |
For back-transformed curves, as in |
mean_type |
Only for |
plot_args |
Superseded by the arguments of |
plot |
Draw the plot now? The default is |
... |
Not used: arguments removed in 2.0 ( |
band |
|
unconditional |
If |
deriv |
|
contr_scale |
With |
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 |
slopes |
With |
pairs |
With |
settings |
The options: |
significant |
With |
plt |
|
pred_df |
The 1.x table: a data.frame with the predicted values, their limits |
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 |
REML |
Logical scalar - Should the estimates be chosen to optimize the REML criterion (as opposed to the log-likelihood)? |
control |
A list (of correct class, resulting from lmerControl() or glmerControl() respectively) containing control parameters, including the nonlinear optimizer to be used and parameters to be passed through to the nonlinear optimizer, see the *lmerControl documentation for details. The default is |
start |
Starting values, as for |
verbose |
Passed on to the lme4 fitting functions. |
drop_unused_levels |
By default unused levels are dropped from factors before fitting. For some smooths involving factor variables you might want to turn this off. Only do so if you know what you are doing. |
subset |
An optional expression indicating the subset of the rows of data that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. |
weights |
An optional vector of <e2><80><98>prior weights<e2><80><99> to be used in the fitting process. Should be NULL or a numeric vector. |
offset |
This can be used to specify an a priori known component to be included in the linear predictor during fitting. This should be NULL or a numeric vector of length equal to the number of cases. One or more offset terms can be included in the formula instead or as well, and if more than one is specified their sum is used. See model.offset. |
contrasts |
An optional list, as |
... |
Further arguments for passing on to model setup routines. Arguments removed in 2.0 ( |
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 |
call |
The call of |
data |
A data.frame with generated variables in the fitting. |
fomul_vars |
Name of variables in the formula of semireg model. |
sm_vars |
Names of the variables of the smooths. |
cov_lst |
Covariance matrix list for each smooth term. |
u_lst |
Random effects list for each smooth term. |
CovMat |
Covariance matrix for all smooth terms. |
Cov_ind |
Covariance matrix index for each smooth term. |
Cov_indN |
Covariance matrix index for each smooth term of several blocks (e.g. |
df |
Degree of freedom of all random terms. |
lmerc |
Call used in the mer model in the fitting. |
smooths |
For smooths written in the formula: the mgcv smooth objects and the maps that give the random-effect
design of each block for new data (used by |
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 |
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 |
ziformula |
a one-sided (i.e., no response variable) formula for zero-inflation combining fixed and random effects: the default |
dispformula |
a one-sided formula for dispersion containing only fixed effects: the default |
weights |
weights, as in |
offset |
offset for conditional model (only). |
contrasts |
an optional list, e.g., |
na.action |
a function that specifies how to handle observations
containing |
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 |
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 |
start |
starting values, expressed as a list with possible components |
map |
a list specifying which parameter values should be fixed to a constant value rather than estimated. |
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. |
... |
Not used: arguments removed in 2.0 ( |
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 |
call |
The call of |
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. |
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 |
... |
Named expressions, one per contrast, e.g. |
.zero_sum |
If |
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 |
what |
Which table: |
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).
meansThe 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, withstatistic(t) andp.valueof slope = 0.pairslevel1,level2, the covariate(s),estimate(level1minuslevel2on the model scale),std.error,df,statistic(t),p.value,conf.low,conf.high;ratioorodds.ratiowith their (pointwise) limits for a log or logit scale; andresponse,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
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 |
object |
A result of |
what |
Which table: |
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 |
|
conf_level |
Confidence level of the intervals; the default is 0.95 ( |
... |
Not used: |
ci_method |
How the intervals of variances are made: |
information |
For REML fits of |
test |
|
test_method |
|
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 |
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