%    Copyright (c) 2012-2016 Russell V. Lenth                                %
%                                                                            %
\documentclass[11pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage{mathpazo}
\usepackage{fancyvrb}
\usepackage{natbib}
\usepackage{hyperref}

\let\dq="
\DefineShortVerb{\"}

\def\pkg#1{\textsf{#1}}
\def\emm{\pkg{emmeans}}
\def\code{\texttt}
\def\proglang{\textsf}

% double-quoted text
\def\dqt#1{\code{\dq{}#1\dq{}}}

% The objects I want to talk about
\def\emmo{\dqt{emmGrid}}

\def\R{\proglang{R}}
\def\SAS{\proglang{SAS}}


\def\Fig#1{Figure~\ref{#1}}
\def\bottomfraction{.5}

\title{Extending \emm{}}
\author{Russell V.~Lenth}

%\VignetteIndexEntry{Extending emmeans}
%\VignetteDepends{emmeans}
%\VignetteKeywords{estimated marginal means}
%\VignettePackage{emmeans}


% Initialization
<<echo=FALSE>>=
options(show.signif.stars=FALSE, prompt="R> ", continue="   ")
set.seed(271828)
@

\begin{document}
\SweaveOpts{concordance=TRUE}
\maketitle{}

\section{Introduction}
Suppose you want to use \emm{} for some type of model that it doesn't (yet) support. Or, suppose you have developed a new package with a fancy model-fitting function, and you'd like it to work with \emm{}. What can you do? Well, there is hope because \emm{} is designed to be extended. 

The first thing to do is to look at the help page for extending the package:
<<eval=FALSE>>=
help("extending-emmeans", package="emmeans")
@
It gives details about the fact that you need to write two S3 methods, "recover_data" and "emm_basis", for the class of object that your model-fitting function returns. The "recover_data"  method is needed to recreate the dataset so that the reference grid can be identified. The "emm_basis" method then determines the linear functions needed to evaluate each point in the reference grid and to obtain associated information---such as the variance-covariance matrix---needed to do estimation and testing.

This vignette presents an example where suitable methods are developed, and discusses a few issues that arise.

\section{Data example}
The \pkg{MASS} package contains various functions that do robust or outlier-resistant model fitting. We will cobble together some \emm{} support for these. But first, let's create a suitable dataset (a simulated two-factor experiment) for testing.\footnote{I unapologetically use \code{=} as the assignment operator. It is good enough for C and Java, and supported by R.}
<<>>=
fake = expand.grid(rep = 1:5, A = c("a1","a2"), B = c("b1","b2","b3"))
fake$y = c(11.46,12.93,11.87,11.01,11.92,17.80,13.41,13.96,14.27,15.82,
           23.14,23.75,-2.09,28.43,23.01,24.11,25.51,24.11,23.95,30.37,
           17.75,18.28,17.82,18.52,16.33,20.58,20.55,20.77,21.21,20.10)
@
The $y$ values were generated using predetermined means and Cauchy-distributed errors. There are some serious outliers in these data.

\section{Supporting \code{rlm}}
The \pkg{MASS} package provides an "rlm" function that fits robust-regression models using $M$~estimation. We'll fit a model using the default settings for all tuning parameters:
<<>>=
library(MASS)
fake.rlm = rlm(y ~ A * B, data = fake)

library(emmeans)
emmeans(fake.rlm, ~B | A)
@
The first lesson to learn about extending \emm{} is that sometimes, it already works! It works here because "rlm" objects inherit from "lm", which is supported by the \emm{} package, and "rlm" objects aren't enough different to create any problems.

\section{Supporting \code{lqs} objects}
The \pkg{MASS} resistant-regression functions "lqs", "lmsreg", and "ltsreg" are another story, however. They create "lqs" objects that are not extensions of any other class, and have other issues, including not even having a "vcov" method. So for these, we really do need to write new methods for "lqs" objects. First, let's fit a model.
<<>>=
fake.lts = ltsreg(y ~ A * B, data = fake)
@

\subsection{The \code{recover\_data} method}
It is usually an easy matter to write a "recover_data" method. Look at the one for "lm" objects:
<<>>=
emmeans:::recover_data.lm
@
Note that all it does is obtain the "call" component and call the method for class \dqt{call}, with additional arguments for its "terms" component and "na.action". It happens that we can access these attributes in exactly the same way as for "lm" objects; so, \ldots
<<>>=
recover_data.lqs = emmeans:::recover_data.lm
@
Let's test it:
<<>>=
rec.fake = recover_data(fake.lts)
head(rec.fake)
@
Our recovered data excludes the response variable "y" (owing to the "delete.response" call), and this is fine. 

\paragraph{Special arguments}
By the way, there are two special arguments "data" and "params" that may be handed to "recover_data" via "ref_grid" or "emmeans" or a related function; and you may need to provide for if you don't use the "recover_data.call" function. The "data" argument is needed to cover a desperate situation that occurs with certain kinds of models where the underlying data information is not saved with the object---e.g., models that are fitted by iteratively modifying the data. In those cases, the only way to recover the data is to for the user to give it explicitly, and "recover_data" just adds a few needed attributes to it. 

The "params" argument is needed when the model formula refers to variables besides predictors. For example, a model may include a spline term, and the knots are saved in the user's environment as a vector and referred to in the call to fit the model. In trying to recover the data, we try to construct a data frame containing all the variables present on the right-hand side of the model, but if some of those are scalars or of different lengths than the number of observations, an error occurs. So you need to exclude any names in "params" when reconstructing the data.

\paragraph{Error handling}
If you check for any error conditions in "recover_data", simply have it return a character string with the desired message, rather than invoking "stop". This provides a cleaner exit. The reason is that whenever "recover_data" throws an error, an informative message suggesting that "data" or "params" be provided is displayed. But a character return value is tested for and throws a different error with your string as the message.

\subsection{The \code{emm\_basis} method}
The "emm_basis" method has four required arguments:
<<>>=
args(emmeans:::emm_basis.lm)
@
These are, respectively, the model object, its "terms" component (at least for the right-hand side of the model), a "list" of levels of the factors, and the grid of predictor combinations that specify the reference grid. 

The function must obtain six things and return them in a named "list". They are the matrix "X" of linear functions for each point in the reference grid, the regression coefficients "bhat"; the variance-covariance matrix "V"; a matrix "nbasis" for non-estimable functions; a function "dffun(k,dfargs)" for computing degrees of freedom for the linear function "sum(k*bhat)"; and a list "dfargs" of arguments to pass to "dffun".

To write your own "emm_basis" function, examining some of the existing methods can help; but the best resource is the "predict" method for the object in question, looking carefully to see what it does to predict values for a new set of predictors (e.g., "newdata" in "predict.lm"). Following this advice, let's take a look at it:
<<>>=
MASS:::predict.lqs
@
\RecustomVerbatimEnvironment{Sinput}{Verbatim}{numbers=left}
Based on this, here is a listing of an "emm_basis" method for "lqs" objects:
<<>>=
emm_basis.lqs = function(object, trms, xlev, grid, ...) {
    m = model.frame(trms, grid, na.action = na.pass, xlev = xlev)
    X = model.matrix(trms, m, contrasts.arg = object$contrasts)
    bhat = coef(object)
    Xmat = model.matrix(trms, data=object$model)
    V = rev(object$scale)[1]^2 * solve(t(Xmat) %*% Xmat)
    nbasis = matrix(NA)
    dfargs = list(df = nrow(Xmat) - ncol(Xmat))
    dffun = function(k, dfargs) dfargs$df
    list(X=X, bhat=bhat, nbasis=nbasis, V=V, dffun=dffun, dfargs=dfargs)
}
@
\RecustomVerbatimEnvironment{Sinput}{Verbatim}{numbers=none}
Before explaining it, let's verify that it works:
<<>>=
emmeans(fake.lts, ~ B | A)
@
Hooray! Note the results are comparable to those we had for "fake.rlm", albeit the standard errors are quite a bit smaller. (In fact, the SEs could be misleading; a better method for estimating covariances should probably be implemented, but that is beyond the scope of this vignette.)

\subsection{Dissecting \code{emm\_basis.lqs}}
Let's go through the listing of this method, by line numbers.
\begin{itemize}
\item[2--3:] Construct the linear functions, "X". This is a pretty standard standard two-step process: First obtain a model frame, "m", for the grid of predictors, then pass it as data to "model.data" to create the associated design matrix. As promised, this code is essentially identical to what you find in "predict.lqs".
\item[4:] Obtain the coefficients, "bhat". Most model objects have a "coef" method.
\item[5--6:] Obtain the covariance matrix, "V", of "bhat". In many models, this can be obtained using the object's "vcov" method. But not in this case. Instead, I cobbled one together using what it would be for ordinary regression: $\hat\sigma^2(\mathbf{X}'\mathbf{X})^{-1}$, where $\mathbf{X}$ is the design matrix for the whole dataset (not the reference grid). Here, $\hat\sigma$ is obtained using the last element of the "scale" element of the object (depending on the method, there are one or two scale estimates). This probably under-estimates the variances and distorts the covariances, because robust estimators have some efficiency loss.
\item[7:] Compute the basis for non-estimable functions. This applies only when there is a possibility of rank deficiency in the model, and "lqs" methods cannot handle that. All linear functions are estimable, and we signal that by setting "nbasis" equal to a $1\times1$ matrix of "NA". If rank deficiency were possible, the \pkg{estimability} package (which is required by \emm{}) provides a "nonest.basis" function that makes this fairly painless---I would have coded:
<<eval=FALSE>>=
nbasis = estimability::nonest.basis(Xmat)
@
On the other hand, if rank-deficient cases are not possible, set "nbasis" equal to "all.estble", a constant in the \pkg{estimability} package.

There is a subtlety you need to know regarding estimability. Suppose the model is rank-deficient, so that the design matrix $\mathbf{X}$ has $p$ columns but rank $r<p$. In that case, "bhat" should be of length $p$ (not $r$), and there should be $p-r$ elements equal to "NA", corresponding to columns of $\mathbf{X}$ that were excluded from the fit. Also, "X" should have all $p$ columns. In other words, do not alter or throw-out columns of "X" or their corresponding elements of "bhat"---even those with "NA" coefficients---as they are essential for assessing estimability. "V" should be $r\times r$, however: the covariance matrix for the non-excluded predictors.
\item[8-9:] Obtain "dffun" and "dfargs". This is a little awkward because it is designed to allow support for mixed models, where approximate methods may be used to obtain degrees of freedom. The function "dffun" is expected to have two arguments: "k", the vector of coefficients of "bhat", and "dfargs", a list containing any additional arguments. In this case (and in many other models), the degrees of freedom are the same regardless of "k". We put the required degrees of freedom in "dfargs" and write "dffun" so that it simply returns that value. (Note: Some models, such as some generalized linear models, do not have a sensible way to determine degrees of freedom. In those cases, return "Inf" degrees of freedom, and asymptotic results
will be computed.)
\item[10:] Return these results in a named list.
\end{itemize}


\section{Hook functions}
Most linear models supported by \emm{} have straightforward structure: Regression coefficients, their covariance matrix, and a set of linear functions that define the reference grid. However, a few are more complex. An example is the \dqt{clm} class in the \pkg{ordinal} package, which allows a scale model in addition to the location model. When a scale model is used, the scale parameters are included in the model matrix, regression coefficients, and covariance matrix, and we can't just use the usual matrix operations to obtain estimates and standard errors. To facilitate using custom routines for these tasks, the "emm_basis.clm" function function provided in \pkg{emmeans} includes, in its "misc" part, the names (as character constants) of two ``hook'' functions: "misc$estHook" has the name of the function to call when computing estimates, standard errors, and degrees of freedom (for the "summary" method); and "misc$vcovHook" has the name of the function to call to obtain the covariance matrix of the grid values (used by the "vcov" method). These functions are called in lieu of the usual built-in routines for these purposes, and return the appropriately sized matrices. 

In addition, you may want to apply some form of special post-processing after the reference grid is constructed. To provide for this, give the name of your function to post-process the object in "misc$postGridHook". Again, \dqt{clm} objects (as well as \dqt{polr} in the \pkg{MASS} package) serve as an example. They allow a "mode" specification that in two cases, calls for post-processing. The \dqt{cum.prob} mode uses the "regrid" function to transform the linear predictor to the cumulative-probability scale. And the \dqt{prob} mode performs this, as well as applying the contrasts necessary to difference the cumulative probabilities into the class probabilities.

\section{Exported methods}
For package developers' convenience, \pkg{emmeans} exports some of its S3 methods for "recover_data" and/or "emm_basis"---use \code{methods(\dqt{recover\_data})} and \code{methods(\dqt{emm\_basis})} to discover which ones. It may be that all you need is to invoke one of those methods and perhaps make some small changes---especially if your model-fitting algorithm makes heavy use of an existing model type supported by \pkg{emmeans}. Contact me if you need \pkg{emmeans} to export some additional methods for your use.

A few additional functions are exported because they may be useful to developers. They are as follows:
\begin{description}
\item[\code{.all.vars(expr, retain)}] Some users of your package may include "$" or "[[]]" operators in their model formulas. If you need to get the variable names, "base::all.vars" will probably not give you what you need. Here is an example:
<<>>=
form = ~ data$x + data[[5]]
base::all.vars(form)
emmeans::.all.vars(form)
@
The "retain" argument may be used to specify regular expressions for patterns to retain as parts of variable names.
\item[\code{.diag(x, nrow, ncol)}]
The base "diag" function has a booby trap whereby, for example, "diag(57.6)" returns a $57\times 57$ identity matrix rather than a $1\times1$ matrix with $57.6$ as its only element. But "emmeans::.diag(57.6)" will return the latter. The function works identically to "diag" except for the identity-matrix trap.
\item[\code{.aovlist.dffun(k, dfargs)}] This function is exported because it is needed for computing degrees of freedom for models fitted using "aov", but it may be useful for other cases where Satterthwaite degrees-of-freedom calculations are needed. It requires the "dfargs" slot to contain analogous contents.
\item[\code{.get.offset(terms, grid)}] If "terms" is a model formula containing an "offset" call, this is will compute that offset in the context of "grid" (a "data.frame").
<<>>=
.get.offset(terms(~ speed + offset(.03*breaks)), head(warpbreaks))
@
\item[\code{.my.vcov(object, ...)}]
In a call to "ref_grid", "emmeans", etc., the user may use "vcov." to specify an alternative function or matrix to use as the covariance matrix of the fixed-effects coefficients. This function supports that feature. Calling ".my.vcov" in place of the "vcov" method will substitute the user's "vcov." when it is present in "...".

\end{description}

\section{Support for \code{rsm} objects}
\RecustomVerbatimEnvironment{Sinput}{Verbatim}{numbers=left, fontsize=\small}
As an example of how an existing package supports \pkg{emmeans}, we show the support offered by the \pkg{rsm} package. Its "rsm" function  returns an \dqt{rsm} object which is an extension of the \dqt{lm} class. Part of that extension has to do with "coded.data" structures whereby, as is typical in response-surface analysis, models are fitted to variables that have been linearly transformed (coded) so that $\pm1$ on the coded scale represents the scope of each predictor. 

Without any extra support in \pkg{rsm}, "emmeans" will work just fine with \dqt{rsm} objects; but if the data are coded, it becomes awkward to present results in terms of the original predictors on their original, uncoded scale. The "emmeans"-related methods in \pkg{rsm} provide a "mode" argument that may be used to specify whether we want to work with coded or uncoded data. The possible values for "mode" are \dqt{asis} (ignore any codings, if present), \dqt{coded} (use the coded scale), and \dqt{decoded} (use the decoded scale). The first two are actually the same in that no decoding is done; but it seems clearer to provide separate options because they represent two different situations.

\subsection{The \code{recover\_data} method}
Note that coding is a \emph{predictor} transformation, not a response transformation (we could have that, too, as it's already supported by the \pkg{emmeans} infrastructure). So, to handle the \dqt{decode} mode, we will need to actually decode the predictors used to construct he reference grid. That means we need to make "recover_data" a lot fancier! Here it is:

%%%\begin{figure}
<<>>=
recover_data.rsm = function(object, data, mode = c("asis", "coded", "decoded"), ...) {
    mode = match.arg(mode)
    cod = rsm::codings(object)
    fcall = object$call
    if(is.null(data))
        data = emmeans::recover_data(fcall, delete.response(terms(object)), object$na.action, ...)
    if (!is.null(cod) && (mode == "decoded")) {
        pred = cpred = attr(data, "predictors")
        trms = attr(data, "terms")
        data = rsm::decode.data(rsm::as.coded.data(data, formulas = cod))
        for (form in cod) {
            vn = all.vars(form)
            if (!is.na(idx <- grep(vn[1], pred))) {
                pred[idx] = vn[2]
                cpred = setdiff(cpred, vn[1])
            }
        }
        attr(data, "predictors") = pred
        new.trms = update(trms, reformulate(c("1", cpred)))   # excludes coded variables
        attr(new.trms, "orig") = trms       # save orig terms as an attribute
        attr(data, "terms") = new.trms
    }
    data
}
@
%%%\end{figure}

Lines 2--6 ensure that "mode" is legal, retrieves the codings from the object, and obtain the results we would get from "recover_data" had it been an \dqt{lm} object. If "mode" is not \dqt{decoded}, \emph{or} if no codings were used, that's all we need. Otherwise, we need to return the decoded data. However, it isn't quite that simple, because the model equation is still defined on the coded scale. Rather than to try to translate the model coefficients and covariance matrix to the decoded scale, we elected to remember what we will need to do later to put things back on the coded scale. In lines~8--9, we retrieve the attributes of the recovered data that provide the predictor names and "terms" object on the coded scale. In line~10, we replace the recovered data with the decoded data. 

By the way, the codings comprise a list of formulas with the coded name on the left and the original variable name on the right. It is possible that only some of the predictors are coded (for example, blocking factors will not be). In the "for" loop in lines~11--17, the coded predictor names are replaced with their decoded names. For technical reasons to be discussed later, we also remove these coded predictor names from a copy, "cpred", of the list of all predictors in the coded model. In line~18, the \dqt{predictors} attribute of "data" is replaced with the modified version.

Now, there is a nasty technicality. The "ref_grid" function in \pkg{emmeans} has a few lines of code after "recover_data" is called that determine if any terms in the model convert covariates to factors or vice versa; and this code uses the model formula. That formula involves variables on the coded scale, and those variables are no longer present in the data, so an error will occur if it tries to access them. Luckily, if we simply take those terms out of the formula, it won't hurt because those coded predictors would not have been converted in that way. So in line~19, we update "trms" with a simpler model with the coded variables excluded (the intercept is explicitly included to ensure there will be a right-hand side even is "cpred" is empty). We save that as the \dqt{terms} attribute, and the original terms as a new \dqt{orig} attribute to be retrieved later. The "data" object, modified or not, is returned. If data have been decoded, "ref_grid" will construct its grid using decoded variables.

\subsection{The \code{emm\_basis} method}
Now comes the "emm_basis" method that will be called after the grid is defined. It is listed below:
<<>>=
emm_basis.rsm = function(object, trms, xlev, grid, 
                         mode = c("asis", "coded", "decoded"), ...) {
    mode = match.arg(mode)
    cod = rsm::codings(object)
    if(!is.null(cod) && mode == "decoded") {
        grid = rsm::coded.data(grid, formulas = cod)
        trms = attr(trms, "orig")   # get back the original terms we saved
    }
    
    m = model.frame(trms, grid, na.action = na.pass, xlev = xlev)
    X = model.matrix(trms, m, contrasts.arg = object$contrasts)
    bhat = as.numeric(object$coefficients) 
    V = emmeans::.my.vcov(object, ...)
    
    if (sum(is.na(bhat)) > 0)
        nbasis = estimability::nonest.basis(object$qr)
    else
        nbasis = estimability::all.estble
    dfargs = list(df = object$df.residual)
    dffun = function(k, dfargs) dfargs$df

    list(X = X, bhat = bhat, nbasis = nbasis, V = V, 
         dffun = dffun, dfargs = dfargs, misc = list())
}
@

This is much simpler. All we have to do is determine if decoding was done (line~5); and, if so, convert the grid back to the coded scale (line~6) and recover the original \dqt{terms} attribute (line~7). The rest is borrowed directly from the "emm_basis.lm" method in \pkg{emmeans}. Note that line~13 uses one of the exported functions we described in the preceding section. Lines 15--18 use functions from the \pkg{estimability} package to handle the possibility that the model is rank-deficient.


\subsection{Exporting the methods}
\RecustomVerbatimEnvironment{Sinput}{Verbatim}{numbers=none, fontsize=\small}
To make the methods available to users of the \pkg{rsm} package, the following code appears in the "NAMESPACE" file:
<<eval = FALSE>>=
if (requireNamespace("emmeans", quietly = TRUE)) {
    importFrom("emmeans", "recover_data", "emm_basis")
    importFrom("estimability", "all.estble", "nonest.basis")
    S3method(recover_data, rsm)
    S3method(emm_basis, rsm)
}
@
This only has an effect if the user has the \pkg{emmeans} package installed (in which case \pkg{estimability} is also installed, as it is required); otherwise the code is skipped. We need to import the prototypes for "recover_data" and "emm_basis", and register our new methods.
Also, packages "emmeans" and "estimability" are included in the "Imports" section of the "DESCRIPTION" file.

Alternatively, we could simply export the functions "recover_data.rsm" and "emm_basis.rsm" without any need to import anything or register methods. It's simpler to do, but makes those functions user-visible and thus they require documentation.

\subsection{A demonstration}
Here's a demonstration of this new support. The standard example for "rsm" fits a second-order model "CR.rs2" to a dataset organized in two blocks and with two coded predictors.
\RecustomVerbatimEnvironment{Sinput}{Verbatim}{numbers=none, fontsize=\normalsize}
<<results = hide>>=
library("rsm")
example("rsm")   ### (output is not shown) ###
@

First, let's look at some results on the coded scale---which are the same as for an ordinary \dqt{lm} object.
<<>>=
emmeans(CR.rs2, ~ x1 * x2, mode = "coded", 
        at = list(x1 = c(-1, 0, 1), x2 = c(-2, 2)))
@
Now, the coded variables "x1" and "x2" are derived from these coding formulas for predictors "Time" and "Temp":
<<>>=
codings(CR.rs1)
@
Thus, for example, a coded value of $x_1=1$ corresponds to a time of $85 + 1\times5 = 90$. Here are some results working with decoded predictors. Note that the "at" list must now be given in terms of "Time" and "Temp":
<<>>=
emmeans(CR.rs2, ~ Time * Temp, mode = "decoded", 
        at = list(Time = c(80, 85, 90), Temp = c(165, 185)))
@
Since the supplied settings are the same on the decoded scale as were used on the coded scale, the EMMs are identical to those in the previous output.


\section{Conclusions}
It is relatively simple to write appropriate methods that work with \emm{} for model objects it does not support. I hope this vignette is helpful for understanding how. Furthermore, if you are the developer of a package that fits linear models, I encourage you to include "recover_data" and "emm_basis" methods for those classes of objects, so that users have access to \pkg{emmeans} support.

\end{document}