---
title: "Robust Multivariate Linear Models"
author: Michael Friendly
date: "`r Sys.Date()`"
package: heplots
output: 
  bookdown::html_document2:
    base_format: rmarkdown::html_vignette
    fig_caption: yes
    number_sections: false
    toc: true
    math_method: mathml
pkgdown:
  as_is: true
bibliography: "robust.bib"
link-citations: yes
csl: apa.csl
vignette: >
  %\VignetteIndexEntry{Robust Multivariate Linear Models}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
  
```{r, include = FALSE}
knitr::opts_chunk$set(
  message = FALSE,
  warning = FALSE,
  fig.height=5,
  fig.width=5,
  fig.align = "center",
  # results='hide',
  # fig.keep='none',
  fig.path='fig/robust-',
  echo=TRUE,
  collapse = TRUE,
  comment = "#>"
)
options(digits = 4)
set.seed(1071)
options(width=80, continue="  ")
```


**Abstract**

This vignette describes the theory behind, and demonstrates the use of, the `robmlm()` function from the `heplots` package, which provides robust estimation for multivariate linear models (MLMs) using iteratively reweighted least squares (IRLS).

It illustrates the central ideas behind robust estimation for MLMs, how the IRLS algorithm works, and presents examples of
plots that help understand how robust models can contribute to data analysis.
It uses two examples, one for a MANOVA design and another for a multivariate multiple regression
to show features of robust methods and the graphical methods of this package that help to
understand them.


**Load packages**

I use the following packages here:
```{r setup}
library(heplots)
library(candisc)
library(ggplot2)
library(dplyr)
library(mvinfluence)
```

## Introduction

Multivariate linear models (MLMs) extend the familiar univariate linear regression framework to situations where multiple response variables are modeled simultaneously as linear functions of a common set of predictor variables. While classical multivariate least squares estimation provides optimal results under ideal conditions (multivariate normality and absence of outliers), real-world data often violate these assumptions. The presence of outliers, heavy-tailed distributions, or other departures from normality can severely compromise the reliability of classical estimators, leading to biased parameter estimates and inflated error rates in hypothesis testing.

The need for robust estimation in _multivariate_ regression has been recognized since the early development of robust statistical methods [@Tukey1960;@Huber1964].
Outliers in multivariate data can be particularly problematic because they may not be readily apparent when examining univariate marginal distributions, yet can exert substantial leverage on the fitted model. Furthermore, the _curse of dimensionality_ means that as the number of response variables increases, the probability of encountering at least one outlying observation grows rapidly.

Robust multivariate regression methods aim to provide reliable parameter estimates and inference procedures that remain stable in the presence of outlying observations. As noted by @Rousseeuw2004, 

>"_The main advantage of robust regression is that it provides reliable results even when some of the assumptions of classical regression are violated._" 


Several approaches have been developed for robust multivariate regression, including M-estimators, S-estimators [@Rousseeuw1984], and MM-estimators [@Yohai1987]. Each approach offers different trade-offs between robustness properties, computational efficiency, and statistical efficiency under ideal conditions. See the [CRAN Task View: Robust Statistical Methods](https://cran.r-project.org/view=Robust) for an extensive list of
robust methods in R. The vignette for the [rrcov package](https://cran.r-project.org/package=rrcov), obtained by `vignette(package = "rrcov")`,
contains a general overview of multivariate robust methods.

The method implemented in the `robmlm()` function belongs to the class of **M-estimators**, which generalize maximum likelihood estimation by replacing the likelihood function with a more robust objective function.

The key idea is to relax the least squares criterion of minimizing $Q(\mathbf{e}) = \Sigma e_i^2 = \Sigma (y_i - \hat{y}_i)^2$ by considering more general functions $Q(\mathbf{e}, \rho)$, where the function $\rho (e_i)$ can be chosen to reduce the impact of large outliers. In these terms,

* OLS uses $\rho(e_i) = e_i^2$
* $L_1$ estimation uses $\rho(e_i) = \vert e_i \vert$, the least absolute values
* A bit more complicated, the **biweight** function uses a squared measure of error up to some value $c$ and then
levels off thereafter,

\[
\rho(e_i) =
\begin{cases} 
\left[ 1 - \left( \frac{e_i}{c} \right)^2 \right]^2 & |e_i| \leq c, \\
1 & |e_i| > c.
\end{cases}
\]

These functions look like this in a graph. The biweight function has a property
like Windsorizing--- the squared error remains constant for residuals $e_i > c$,
with $c = 4.685$ for `MASS::psi.bisquare()`.


```{r echo=FALSE, out.width="70%"}
#| label: fig-weight-fns
#| fig-align: "center"
#| fig-cap: "Diagram ploting the function $\\rho(e_i)$ of the contributions of the residuals $e_i$ to what is minimized in various fitting methods."
knitr::include_graphics(here::here("man", "figures", "weight-functions.jpg"))
```



## Methodology: Iteratively Reweighted Least Squares (IRLS)

The `robmlm()` function implements robust multivariate linear model fitting using Iteratively Reweighted Least Squares (IRLS), a flexible and computationally efficient approach that belongs to the family of M-estimators. The core idea behind IRLS is to iteratively downweight observations that appear to be outliers based on their residual distances from the fitted model.

### The IRLS Algorithm

The IRLS algorithm for robust multivariate regression is shown in the figure below.

```{r echo=FALSE, fig.align='center', out.width="70%", fig.cap="Flowchart for the iteratively reweighted least squares algorithm"}
knitr::include_graphics(here::here("man", "figures", "IRWLS-flowchart.jpg"))
```

The method proceeds as follows:

1. **Initialization**: Begin with an initial estimate of the regression coefficients, typically obtained from ordinary least squares (OLS).

2. **Residual calculation**: Compute the multivariate residuals for each observation:
   $$\mathbf{r}_i = \mathbf{y}_i - \mathbf{X}_i\hat{\boldsymbol{\beta}}$$
   where $\mathbf{y}_i$ is the $p \times 1$ response vector for observation $i$, $\mathbf{X}_i$ is the corresponding row of the design matrix, and $\hat{\boldsymbol{\beta}}$ is the current estimate of the coefficient matrix.

3. **Distance computation**: Calculate the squared Mahalanobis distance of each residual vector from the origin:
   $$d_i^2 = \mathbf{r}_i^T \mathbf{S}^{-1} \mathbf{r}_i$$
   where $\mathbf{S}$ is a robust estimate of the residual covariance matrix, computed using `MASS::cov.trob()`.

4. **Weight assignment**: Assign weights to each observation based on their residual distances. Observations with larger distances receive smaller weights, effectively downweighting potential outliers:
   $$w_i = \rho(d_i^2)$$
   where $\rho(\cdot)$ is a weight function that decreases as the distance increases.

5. **Weighted Least Squares**: Update the coefficient estimates using weighted least squares:
   $$\hat{\boldsymbol{\beta}}^{(new)} = (\mathbf{X}^T\mathbf{W}\mathbf{X})^{-1}\mathbf{X}^T\mathbf{W}\mathbf{Y}$$
   where $\mathbf{W}$ is a diagonal matrix of weights.

6. **Convergence check**: Repeat steps 2-5 until convergence, typically assessed by monitoring changes in the coefficient estimates or weights between iterations.

### Features of the Implementation

The `robmlm()` implementation incorporates several important features:

- **Robust covariance estimation**: The use of `MASS::cov.trob()` provides a robust estimate of the residual covariance matrix, which is crucial for computing meaningful Mahalanobis distances in the presence of outliers.
This uses the multivariate $t$ distribution that allows for longer tails.
(There are other robust covariance estimators, such as Minimum Covariance Determinant (MCD) and Minimum Volume Ellipse (MVE), which have a high tolerance---breakdown-bound-- for outliers. These might come to a future version of `robmlm()`.)

- **Inheritance Structure**: The returned object inherits from both `"mlm"` and `"lm"` classes, ensuring compatibility with existing R infrastructure for linear models while adding robust-specific methods.

- **Weight Preservation**: The final weights are preserved in the fitted object, allowing users to identify influential observations and assess the impact of the robust fitting procedure.

- **Diagnostic Capabilities**: The `plot.robmlm()` method provides immediate visual feedback on the weighting scheme, plotting final weights against case numbers to highlight observations that were down-weighted during the fitting process.

- **Visualization methods**: Because a fitted `robmlm` object inherits the `"mlm"` class, it works directly with `heplots`' existing diagnostic and hypothesis-test plots. `distancePlot()` plots the Mahalanobis distances of the model-matrix predictors against the distances of the residuals, so cases with both high leverage and a large residual --- and so likely down-weighted during IRLS --- stand out just as they would for a classical `mlm`. `heplot()` goes further: fitting the classical and robust models separately and overlaying the robust **H** and **E** ellipses on the classical model's plot (`add = TRUE`) gives a direct geometric view of how down-weighting outliers reshapes the hypothesis and error variation --- typically a visibly smaller **E** ellipse for the robust fit. See the example below.

### Theoretical Properties

The IRLS approach offers several desirable theoretical properties:

- **Breakdown Point**: While not achieving the highest possible breakdown point, M-estimators like those implemented in IRLS can handle a reasonable proportion of outliers before completely breaking down.

- **Influence Function**: The bounded influence function of M-estimators ensures that no single observation can have unlimited impact on the final estimates.

- **Asymptotic Efficiency**: Under ideal conditions (no outliers, multivariate normality), robust M-estimators achieve high efficiency relative to classical least squares estimators.

- **Equivariance**: The robust estimates maintain appropriate equivariance properties under linear transformations of the data.

<!--
## Structure of This Vignette

In the following sections, we will demonstrate the practical application of `robmlm()` through several illustrative examples:

1. **Basic Usage**: Simple examples showing how to fit robust multivariate linear models and interpret the results.

2. **Comparison with Classical Methods**: Side-by-side comparisons highlighting the differences between robust and classical estimates in the presence of outliers.

3. **Diagnostic Tools**: Detailed exploration of diagnostic methods, including weight plots and residual analysis.

4. **Real Data Applications**: Examples using datasets from the `heplots` package and other sources that demonstrate the practical utility of robust estimation.

5. **Advanced Topics**: Discussion of model selection, hypothesis testing, and confidence intervals in the robust multivariate regression context.

Each example will include both the R code and interpretation of results, with particular attention to how robust methods can provide more reliable insights when data quality is questionable.
-->


## Example: Pottery Data

We begin with a simple but illustrative example using the pottery composition data from the `carData` package. This dataset contains measurements of five chemical elements (`Al`, `Fe`, `Mg`, `Ca`, `Na`) in pottery samples from four different archaeological sites. The goal is to determine whether the chemical composition differs significantly across sites, a classic one-way MANOVA problem. Alternatively, it can be framed as a problem in discriminant analysis, asking whether
these chemical elements can be used to distinguish among the sites.

```{r pottery-data, message=FALSE}
library(heplots)
library(carData)
library(car)

# Load the pottery data
data(Pottery, package = "carData")
head(Pottery)
```

The pottery dataset contains `r nrow(Pottery)` observations with measurements of five response variables representing chemical concentrations. Let's examine the basic structure:

```{r pottery-structure}
str(Pottery)
```
The pottery samples are not evenly distributed across the sites. The most come from Llanedryn; there are only two from
Caldicot.

```{r}
table(Pottery$Site)
```


### Classical MANOVA

We begin with the standard MANOVA model, and then examine some diagnostic plots.

```{r pottery-mlm}
# Classical MANOVA model
pottery.mlm <- lm(cbind(Al, Fe, Mg, Ca, Na) ~ Site, data = Pottery)
Anova(pottery.mlm)
```

**Chisquare QQ plot**:
As an initial check, a `cqplot()` of the model gives a $\chi^2$ QQ plot of the residuals from the model,
which would identify badly fit observations. None seem particularly large here.

```{r pottery-cqplot, fig.cap="Chisquare QQ plot for the Pottery model."}
cqplot(pottery.mlm, id.n = 5)
```
**Influence plot**:
An _influence plot_ for this model, done using `mvinfluence::influencePlot()` plots the leverage multivariate hat-values for the predictors (`site`) against squared multivariate studentized residuals, using the size of the point symbol proportional to a multivariate generalization of Cook's D statistic. 

```{r pottery-inflplot, fig.cap = "Influence plot for the Pottery model."}
res <- influencePlot(pottery.mlm, id.n = 2)
res |>
  arrange(desc(CookD))
```

Because `site` is a factor, the hat-values are inversely proportional to the sample size. Points for Llanedryn ($n=14$) are in the
left-most column, followed by AshleyRails and IsleThorns (each with $n=5$) and then Caldicot ($n=14$).

Here, case 25 stands out with the largest value of Cook's D, followed by 18 and 11. 

### Robust MANOVA

Now, fit the robust model using `robmlm()`. Because this uses an iterative IRLS method, points that might not seem unusual
in the initial model can become more noteworthy when the extreme observations are down-weighted in a subsequent iteration.

```{r pottery-rlm}
# Robust MANOVA model
pottery.rlm <- robmlm(cbind(Al, Fe, Mg, Ca, Na) ~ Site, data = Pottery)
Anova(pottery.rlm)
```

Let's compare the results. From the results of `Anova()` above, you can see that
the $F$ statistic for the robust model is greater than that for OLS,
which suggests that possible outliers may have reduced the strength of evidence for differences among the sites.

It is useful to compare the coefficients of the two models, and for this, their relative difference is
a useful metric. The simple function `reldiff()` expresses these as the signed percent of difference
between the classical and robust estimates.

```{r pottery-coefs}
b.mlm <- coef(pottery.mlm)
b.rlm <- coef(pottery.rlm)

reldiff <- function(x, y, pct=TRUE) {
  res <- abs(x - y) / x
  if (pct) res <- 100 * res
  res
}

reldiff(b.mlm, b.rlm)
```

Among these, the coefficients for IsleThorns are quite different for most of the variables.

### Examining the Robust Weights

The robust fitting procedure assigns weights to each observation based on their deviation from the fitted model. Observations that appear to be outliers receive lower weights. The `plot()` method for a `"roblm"` object gives an index plot of the weight values.

```{r pottery-weights, fig.cap="Weights from robust MANOVA fitting showing potential outliers"}
# Plot the weights from robust fitting
plot(pottery.rlm, col=Pottery$Site, segments=TRUE)
xloc <- c(7.5, 15.5, 19.5, 24)
text(xloc, rep(c(1.0, 1.05), length=5), 
     levels(Pottery$Site), pos =3, xpd = TRUE)
```

The weight plot reveals which observations were considered potentially problematic during the robust fitting process. Observations with weights substantially below 1.0 were down-weighted, indicating they may be outliers in the multivariate space defined by the five chemical measurements.

### Distance Plot

`distancePlot()` gives a complementary view of the same idea. It plots the Mahalanobis distances of the `Site` **predictors** (the model matrix `X`) against the distances of the **residuals** from the robust fit, labeling cases beyond the cutoff lines (dashed, `level = 0.975` by default). This plot method, due to
Rousseeuw & van Zomeren [-@Rousseeuw1990; -@Rousseeuw1991] and Rousseeuw et al. [-@Rousseeuw2004], helps you see WHY observations are
downweighted, by combining information on regression outliers (unusual in the `Y` responses) and leverage points
(unusual in the `X`s).

```{r pottery-distanceplot, fig.cap="Distance plot for the robust Pottery model: Mahalanobis distances of the Site predictors vs. distances of the residuals."}
distancePlot(pottery.rlm)
```

Case 25 -- already flagged with the largest Cook's D in the classical influence plot above -- again stands out,
here with an unusually large residual distance. Cases 15 and 16 stand out instead on the predictor (`Site`) side,
reflecting their group's small sample size rather than an unusual response pattern.

### Hypothesis-Error (HE) plots

HE plots provide a visual representation of the multivariate hypothesis test by showing the relationship between hypothesis and error variation in a reduced dimensional space. We'll create HE plots for the first two variables (Al and Fe) and compare the classical and robust fits.

```{r pottery-heplot, fig.cap="HE plot comparing classical (blue) and robust (red) MANOVA for Al vs Fe", fig.width=8, fig.height=6}
# Classical HE plot for Al and Fe
heplot(pottery.mlm, variables = c("Al", "Fe"), 
       main = "Classical vs Robust MANOVA: Al vs Fe",
       col = c("blue", "blue"), fill = TRUE, fill.alpha = 0.2)

# Overlay robust HE plot
heplot(pottery.rlm, variables = c("Al", "Fe"), 
       add = TRUE, error.ellipse = TRUE,
       col = c("red", "red"), 
       fill = TRUE, fill.alpha = 0.2, lty = 2)

# Add legend
legend("topright", 
       legend = c("Classical", "Robust"), 
       col = c("blue", "red"), 
       lty = c(1, 2), 
       fill = c("blue", "red")
       )
```

The **H** and **E** ellipses have approximately the same shape and orientation for the classical and robust models, indicating
that the pattern of differences among the group means is quite similar for both models. However, the **E** ellipse for the robust
model is noticeably smaller. This goes into the greater $F$ statistic for the robust model.

For a more complete interpretation of robust model, a scatterplot matrix of HE plots is shown below, using the `pairs()` method
for a MLM.

```{r pottery-pairs, fig.cap = "Pairwise HE plots for all response variables in the robust model `pottery.rlm`"}
pairs(pottery.rlm, 
      fill=TRUE, fill.alpha = 0.1)
```


### Interpretation and Discussion

Several important insights emerge from this analysis of the Pottery data

* **Model evaluation**: The comparison of MANOVA results shows ...

<!--
|r ifelse(abs(log10(robust_anova$"Pr(>F)"[1]) - log10(classical_anova$"Pr(>F)"[1])) > 0.5, "substantial differences", "similar patterns")| between classical and robust approaches. 
This indicates |r ifelse(abs(log10(robust_anova$"Pr(>F)"[1]) - log10(classical_anova$"Pr(>F)"[1])) > 0.5, "that outliers are influencing the classical analysis", "that the data are relatively well-behaved with respect to outliers")|.
-->

* **Outlier detection**: The weight plot identifies specific observations that deviate from the typical pattern. In archaeological studies, such outliers might represent pottery from different time periods, contaminated samples, or measurement errors that warrant further investigation.

* **Geometric interpretation**: The HE plot comparison reveals how outliers affect the geometric representation of the hypothesis test. The hypothesis ellipse (representing the Site effect) and error ellipse (representing within-group variation) may differ substantially between classical and robust fits when influential outliers are present. The usual effect is that of seeing hypothesis effects more strongly
when potential outliers are down-weighted.

* **Practical implications**: For archaeologists studying historical artifacts, the robust analysis provides more reliable conclusions about site or other factors differences by reducing the influence of potentially problematic observations. This is particularly important when making inferences about ancient trade routes, cultural practices, or chronological relationships based on chemical composition data. In some circumstances, the identification of such unusual observations can lead to insight about conventional theory.

The robust approach demonstrates its value by providing a more stable analysis that is less susceptible to the influence of outlying observations, while still maintaining high efficiency when the data conform to standard assumptions.

## Example: Pulp Fiber Data

Our second example is more compact, and illustrates `robmlm()` in a  multivariate multiple regression rather than a MANOVA design. The `pulpfiber` data [in the `robustbase` package, @Rousseeuw2004; data from the unpublished thesis of Lee, 1992] give four pulp-fiber properties (`X1`-`X4`: fiber length, long fiber fraction, fine fiber fraction, zero-span tensile) measured on 62 samples, along with four properties of the paper produced from them (`Y1`-`Y4`: breaking length, elastic modulus, failure stress, burst strength). The goal is to predict the paper properties from the fiber properties.

```{r pulpfiber-data, message=FALSE}
data(pulpfiber, package = "robustbase")
str(pulpfiber)
```

### Classical and Robust Fits

To get started, fit the classical OLS multivariate regression and the robust version and run `car::Anova()` on each

```{r pulpfiber-fit}
pulp.mod <- lm(cbind(Y1, Y2, Y3, Y4) ~ X1 + X2 + X3 + X4, data = pulpfiber)
pulp.rlm <- robmlm(cbind(Y1, Y2, Y3, Y4) ~ X1 + X2 + X3 + X4, data = pulpfiber)

Anova(pulp.mod)
Anova(pulp.rlm)
```

The contrast here is more dramatic than for Pottery: 

* In the classical fit, `X2` and `X4` stand out clearly ($p < .0001$), `X3` is only marginally significant ($p = .011$), and `X1` falls just short of conventional significance ($p = .053$). 
* In the robust fit, by contrast, all four fiber properties are highly significant predictors of the paper properties ($p < .001$ in every case). This suggests that a handful of atypical samples in the classical fit are masking real predictive relationships involving `X1` and `X3`.

### Robust Weights

```{r pulpfiber-weights, fig.cap="Weights from robust fitting of the pulp fiber data"}
plot(pulp.rlm, segments = TRUE)
```

Four cases -- 51, 52, 56 and 61 -- are driven to (essentially) zero weight; two more (22, 44) are markedly reduced (0.43 and 0.69); every other sample retains weight above 0.7. The weight plot alone doesn't say *why* these six are atypical; for that we turn to the distance plot.

### Distance Plot

A `distancePlot()` involves two independent choices: which residuals define the `Y` (vertical) axis -- from `pulp.mod` (OLS) or `pulp.rlm` (robust) -- and which covariance estimator computes the distances themselves, via `method`. In this example, only the second choice matters much: with the default `method = "classical"`, the flagged cases are *identical* whether the residuals come from `pulp.mod` or `pulp.rlm` -- the same eight cases (46, 51, 52, 56, 57, 58, 60, 61) either way. The main difference is seen in the covariance estimate, not the fit.

The reason is a masking effect: classical covariance for the `X1`-`X4` fiber measurements is computed from all 62 samples, including the very outliers it is meant to help detect, so it is itself distorted by them and understates how unusual those samples really are. Rousseeuw et al. [-@Rousseeuw2004] address exactly this for the pulp fiber data by using the MCD covariance estimator instead, which is resistant to the outliers it's estimating around. The panels below compare the two, both using the robust-fit residuals from `pulp.rlm`:

```{r pulpfiber-distanceplot, fig.width=9, fig.height=4.5, fig.cap="Distance plots for the robust pulp fiber model, comparing classical (left) and MCD-based (right) covariance estimates for the fiber (X) predictor distances."}
op <- par(mfrow = c(1, 2))
distancePlot(pulp.rlm, method = "classical", main = "Classical distances")
distancePlot(pulp.rlm, method = "mcd", main = "MCD distances")
par(op)
```

Under classical covariance (left), cases 60 and 62 -- which turn out to have the two largest predictor distances of any sample once MCD is used -- don't stand out at all: their unusual fiber measurements are masked by a covariance matrix that treats them as ordinary. Under MCD (right), the picture sharpens considerably, flagging 21 cases rather than 8. Most of these retain weight above 0.8 in `pulp.rlm` -- unusual in `X`, but well fit by the model -- so we focus on the few that also matter for the robust fit:

* Cases 51, 52 and 56 have unremarkable fiber measurements (small distance on `X`) but very large residual distances: **vertical outliers**, poorly predicted by the fitted relationship regardless of their (ordinary) predictor values. These are exactly the three cases driven to zero weight above.

* Case 61 is extreme on *both* axes: a **bad leverage point**, unusual in its fiber properties *and* poorly fit by the model -- correctly downweighted to zero along with the vertical outliers.

* Cases 60 and 62 have the two largest predictor distances of any sample, by a wide margin, yet small residual distances: **good leverage points**. They are unusual fiber samples, but ones the fitted relationship predicts well, so `robmlm()` correctly leaves them at near-full weight (0.98 each) rather than downweighting them.

* Case 22 sits in between, at weight 0.43: moderately unusual on both axes without being fully downweighted -- a reminder that `robmlm()`'s weighting is continuous, not the all-or-nothing split the labels above suggest.

### Interpretation and Discussion

* **Model evaluation**: The gain from 2 to 4 significant predictors under the robust fit shows how a small number of outlying samples can mask genuine predictive relationships in classical multivariate regression -- a stronger contrast than in the Pottery example.

* **Outlier detection**: The weight plot and distance plot together tell a more nuanced story than "outlier" vs. "not": some flagged cases (51, 52, 56, 61) are poorly fit and rightly downweighted, while others (60, 62) are merely unusual in their predictors and rightly are not. Distinguishing good from bad leverage points this way is exactly the diagnostic problem `distancePlot()` is designed to address.

* **Practical implications**: For process data like this -- where fiber properties are measured to predict paper quality -- correctly identifying *which* atypical samples to downweight (vertical/bad-leverage cases) versus keep (good-leverage cases) matters for building a model that generalizes to new, unusual-but-plausible fiber batches, rather than one that has simply been fit to accommodate a few mismeasured samples.

## References
