% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/nested.R
\name{add_grouping}
\alias{add_grouping}
\title{Add a grouping factor}
\usage{
add_grouping(object, newname, refname, newlevs)
}
\arguments{
\item{object}{An \code{emmGrid} object}

\item{newname}{Character name of grouping factor to add (different from any
existing factor in the grid)}

\item{refname}{Character name of the reference factor}

\item{newlevs}{Character vector or factor of the same length as that of the levels for 
\code{refname}. The grouping factor \code{newname} will have the unique
values of \code{newlevs} as its levels.}
}
\value{
A revised \code{emmGrid} object having an additional factor named 
  \code{newname}, and a new nesting structure \code{refname \%in\% newname}
}
\description{
This function adds a grouping factor to an existing reference grid or other 
\code{emmGrid} object, such that the levels of an existing factor (call it the
reference factor) are mapped to a smaller number of levels of the new
grouping factor. The reference factor is then nested in the grouping factor. 
This facilitates obtaining marginal means of the grouping factor, and 
contrasts thereof.
}
\note{
By default, the levels of \code{newname} will be ordered
  alphabetically. To dictate a different ordering of levels, supply 
  \code{newlevs} as a \code{factor} having its levels in the required order.
}
\examples{
fiber.lm <- lm(strength ~ diameter + machine, data = fiber)
( frg <- ref_grid(fiber.lm) )

# Suppose the machines are two different brands
brands <- factor(c("FiberPro", "FiberPro", "Acme"), levels = c("FiberPro", "Acme"))
( gfrg <- add_grouping(frg, "brand", "machine", brands) )

emmeans(gfrg, "machine")

emmeans(gfrg, "brand")
}
