---
title: "Getting started with predictmeans"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting started with predictmeans}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE, warning = FALSE,
                      fig.width = 7, fig.height = 4.5)
```

predictmeans gives predicted (least-squares) means, standard errors, LSDs and pairwise
comparisons for `lm`, `glm`, `aov`, `gls`, `lme`, `lmer`, `glmer`, `glmmTMB` and `gam`
models, with Kenward–Roger or Satterthwaite degrees of freedom for mixed models, and
permutation tests.

```{r, echo = FALSE, out.width = "100%", fig.alt = "From a fitted model to the report: diagnostics, tests, means and contrasts, variance components, then tables and plots"}
knitr::include_graphics("../man/figures/workflow.png")
```

## Why predictmeans

- **Defaults chosen on evidence** (simulation, literature): Kenward–Roger df and
  adjusted SEs for REML `lmer` fits; permutation p-values $(b+1)/(B+1)$; `aov` with
  `Error()` analysed by strata, with SEs from the stratum mean squares (as Genstat);
  means over empty cells averaged with equal weight over the observed cells, with a
  warning naming them.
- **Checked against outside references** in the package tests: real SAS PROC MIXED
  and Genstat runs (`vignette("sas")`), pbkrtest, `nlme::lme` and emmeans.
- **Robust across model classes**: when a result cannot be computed correctly, the
  function stops with a message saying why, rather than returning a wrong number.
- **Advice from the data**: when this fit needs a caution (empty cells, singular fit,
  small df, ...), the result says so in one line with what to do; read it with
  `advice(x)`, turn it off with `options(predictmeans.advice = FALSE)`.
- **Reproducible**: permutation and bootstrap results are identical for any `ncore`.

## A split-plot experiment

The oats data (Yates 1935) are a split plot: three varieties on whole plots within six
blocks, four nitrogen levels on subplots.

```{r}
library(predictmeans)
Oats <- as.data.frame(nlme::Oats)
Oats$nitro <- factor(Oats$nitro)
fm <- lmer(yield ~ nitro * Variety + (1 | Block/Variety), data = Oats)
```

## Predicted means and pairwise comparisons

```{r}
pm <- predictmeans(fm, "nitro:Variety", atvar = "Variety", adj = "tukey")
summary(pm)
```

`atvar = "Variety"` compares the nitrogen levels within each variety, with Tukey
adjustment within each variety.

## Tables to work with

Every result carries three stable tables: `means`, `pairs` and `settings`. They are plain
data frames, so they are easy to filter, join or export.

```{r}
head(pm$means)
head(pm$pairs)
```

The same tables come from `as.data.frame()` or, with the generics package, `tidy()`:

```{r}
head(as.data.frame(pm, what = "pairs"), 3)
```

## Plots

```{r}
ggplot2::autoplot(pm)
ggplot2::autoplot(pm, type = "pvalue")
```

`autoplot()` draws every plot from the result (`predictmeans()` draws none): the means with one average LSD
bar (the default), `type = "bar"`, `type = "ci"` (each mean with its confidence limits; on the response scale when
the means are back-transformed) and `type = "pvalue"`. `data = TRUE` adds the observations; `x`, `group` and
`panel` place the factors; with `atvar` each level is a panel with its own LSD.

```{r}
ggplot2::autoplot(pm, type = "bar")
ggplot2::autoplot(pm, type = "ci", data = TRUE)
```

## Degrees of freedom and standard errors

`df_method = "auto"` (the default) chooses the df by the model:

| Model | Default df | Other choices of `df_method` |
|---|---|---|
| REML `lmer`, `lme`, `gls` | Kenward–Roger, with adjusted SEs (as SAS `DDFM=KR`) | `"Satterthwaite"`, `"containment"`, `"between-within"`, `"KR-expected"`, `"KR-average"` |
| ML `lmer`, `lme`, `gls` | Satterthwaite, from the ML likelihood | `"containment"`, `"between-within"` |
| `glmer`, `glmmTMB` | `"inner-outer"`: the df of the grouping level at which each effect varies | `"containment"`, `"between-within"` (`glmer`), `"residual"` |
| `glm`, `gam`: Poisson, binomial, negative binomial | none: z tests (`"asymptotic (z)"`), as emmeans and SAS GLIMMIX | `"residual"` (t tests, as 1.x) |
| `lm`; `glm`, `gam` with an estimated dispersion (Gaussian, Gamma, quasi-) | residual df | |
| `aov` with `Error()` | by strata, Satterthwaite's df across strata | |

`settings$df_method` of the result says which was used. For the split plot (a REML
`lmer` fit) the default gives Kenward–Roger SEs and df. Other choices:

```{r}
# Satterthwaite df
pm_s <- predictmeans(fm, "Variety", df_method = "Satterthwaite")
# SAS DDFM=CONTAIN (containment) df, with unadjusted standard errors
pm_c <- predictmeans(fm, "Variety", df_method = "containment")
rbind(Satterthwaite = pm_s$means$df[1], containment = pm_c$means$df[1])
```

`df_method = "between-within"` gives SAS's `DDFM=BETWITHIN` df. Kenward–Roger uses the
observed information of the variance parameters, as SAS does; `"KR-expected"` uses the
expected information, as pbkrtest and emmeans. The two agree in balanced designs; with
missing values only the observed information is valid, and in simulations it kept the
5% level where the expected one rejected 8.5% of true hypotheses. `"KR-average"` uses the average
information of Genstat's REML and gives Genstat's df (with `vcov_adjust = FALSE`, also its SEDs). For
`lme` and `gls` models with correlation or variance structures, `"Satterthwaite"`, `"Kenward-Roger"`,
`"KR-expected"` and `"KR-average"` are available too. `vignette("sas", package = "predictmeans")` shows how each matches SAS PROC
MIXED.

ML fits get Satterthwaite df because Kenward–Roger's adjustment is derived for REML. For
Poisson, binomial and negative binomial `glm` fits the dispersion is known, so there are
no residual df to use: in simulations, t tests on the residual df rejected 0.3–4.5% of
true hypotheses at the 5% level, and z tests 3.6–5.7%.

Before reading the means, check the model: `pm_check()` and `residplot()`, in
`vignette("checking", package = "predictmeans")`.

## Averaging over other factors

Means of a main effect average over the other factors in the model. `weights` chooses
how: `"equal"` (the default), `"proportional"` (as SAS `LSMEANS / OM`), `"outer"`,
`"cells"` or `"flat"`, with the same definitions as emmeans.

```{r}
predictmeans(fm, "nitro", weights = "proportional")$means
```

## Contrasts

`contrastmeans()` tests contrasts among the means: comparisons with a control, trends,
contrasts written by the names of the means (`specify_contrast()`), joint tests and slopes.
They are worked through in `vignette("contrasts", package = "predictmeans")`.

## Covariates and the reference grid

`Kmatrix()` builds the reference grid behind every mean. Covariates are set to their means
by default (`cov_reduce` changes that), and may enter the model through transformations
such as `poly()`, `ns()`, `log()` or smooth terms of a `gam`. Here the drug means are at the
mean log dose:

```{r}
data(Drug)
fm_glm <- glm(cbind(R, N - R) ~ Drug + log10Dose, family = binomial, data = Drug)
predictmeans(fm_glm, "Drug", pairwise = TRUE)$means
```

For a glm the means are also given on the response scale (here probabilities); see
`vignette("response-scale")`.

## When to use predictmeans, emmeans or marginaleffects

predictmeans has been on CRAN since July 2014, before emmeans (2017; its predecessor lsmeans from 2012) and
marginaleffects (2021). Version 2.0 rewrote its inference and checked it against SAS, Genstat and emmeans.
The three packages agree where they should: for linear and standard mixed models with equal weights,
predictmeans' means, SEs and pairs equal emmeans' (checked in the tests).

**Where predictmeans is the better choice: designed experiments and mixed models.**

- *Degrees of freedom for mixed models*, checked against SAS PROC MIXED and Genstat: Kenward–Roger by default for
  `lmer`, `lme` and `gls` (with prior weights and offsets), Satterthwaite, containment, between-within, and
  inner-outer df for GLMMs. emmeans takes Kenward–Roger and Satterthwaite from pbkrtest/lmerTest for `lmer` only;
  marginaleffects uses z tests unless told otherwise.
- *Outputs of designed experiments*: LSDs, letters, comparison intervals whose overlap matches the test, SED
  tables, and `aov` with `Error()` analysed by strata as Genstat does, missing plots included.
- *Unbalanced data*: a stated rule for empty cells, aliased covariates and factors confounded in the data, each
  with a warning, where emmeans often gives NA.
- *Permutation and bootstrap inference*: Freedman–Lane permutations for linear, mixed and generalized mixed models,
  Westfall–Young adjustment, permutation limits.
- *Smooth curves in mixed models*: `semireg()` and `semipred()` with curves, derivatives and tests of equal curves.
- *Advice from this fit and these data* stored in every result, and one package for variance components and their
  tests, heritability, R² of mixed models, diagnostics and variograms.

**Where emmeans or marginaleffects is the better choice.**

- *Many more model classes.* predictmeans has its own code for about 20 (see the table below, plus `mmrm` and
  `betareg`); others are handled through emmeans' basis (the article
  [Other model classes](https://dongwenluo.github.io/predictmeans/articles/other-classes.html)), with
  means, pairs and contrasts but not permutation tests, `varcomp()` or R².
- *Quantities that are not linear in the coefficients*: marginaleffects gives response-scale contrasts, ratios,
  average marginal effects and counterfactual predictions for any function. predictmeans works on the linear
  predictor and back-transforms (zero-inflated `glmmTMB` means are the exception).
- *Bayesian fits*: predictmeans works on the draws of `brms` and `rstanarm` fits (article
  [Bayesian fits](https://dongwenluo.github.io/predictmeans/articles/bayesian.html)) for the families listed
  there; for other families use emmeans or marginaleffects.
- *Contrast syntax*: emmeans' nested contrasts, contrast families and `regrid` are richer.
- *Fewer dependencies*: marginaleffects is light; predictmeans imports lme4, nlme, glmmTMB, mgcv and ggplot2.

Two differences are by design. With nested treatments or missing combinations predictmeans averages with equal
weights over the combinations that exist, where emmeans weights by the nesting or gives NA
(`vignette("missing-cells")`); and its default df for mixed models is Kenward–Roger.

In short: for field trials, animal and plant experiments and repeated measures, predictmeans is the natural
default; for observational data, non-linear quantities or unusual model classes, use emmeans or
marginaleffects. The packages work together: predictmeans can borrow emmeans' basis, and its numbers can be
checked against emmeans.

## Where to go next

- `vignette("checking", package = "predictmeans")`: checking the model with `pm_check()`
  and `residplot()`.
- `vignette("contrasts", package = "predictmeans")`: other adjustments for multiple
  testing, comparisons with a control, trends, joint tests (slices) and slopes.
- `vignette("response-scale", package = "predictmeans")`: GLMs, GLMMs and transformed
  responses: means and standard errors on the response scale, ratios and odds ratios.
- `vignette("missing-cells", package = "predictmeans")`: empty cells, confounded factors
  and means that cannot be estimated.
- `vignette("R2_glmm", package = "predictmeans")`: adjusted R² for mixed models.
- `vignette("migrating", package = "predictmeans")`: what changed from version 1.x.
- `vignette("resampling", package = "predictmeans")`: permutation and parametric
  bootstrap tests (`permmodels()`, `permlmer()`, `permindex()`, `bootmodels()`) for
  linear, generalized linear and mixed models, also for pairwise comparisons and
  contrasts through `permlist`.
- `vignette("smooth", package = "predictmeans")`: smooth curves in mixed models
  (`semireg()`, `semipred()`), with simultaneous confidence bands.
