---
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
```

## Custom contrasts

`specify_contrast()` writes contrasts by the names of the means; `contrastmeans()` tests
them.

```{r}
cm <- specify_contrast(Kmatrix(fm, "nitro:Variety"),
  N_effect_Victory = `0.6:Victory` - `0:Victory`,
  N_effect_Victory_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)
```

## Models with covariates

`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`.

```{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")`.

## More

- `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.
