\HeaderA{contrasts}{Get and Set Contrast Matrices}{contrasts}
\aliasA{contrasts<\Rdash}{contrasts}{contrasts<.Rdash.}
\keyword{design}{contrasts}
\keyword{regression}{contrasts}
\begin{Description}\relax
Set and view the contrasts associated with a factor.
\end{Description}
\begin{Usage}
\begin{verbatim}
contrasts(x, contrasts = TRUE)
contrasts(x, how.many) <- value
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{x}] a factor or a logical variable.
\item[\code{contrasts}] logical.  See \sQuote{Details}.
\item[\code{how.many}] How many contrasts should be made. Defaults to one
less than the number of levels of \code{x}.  This need not be the
same as the number of columns of \code{value}.
\item[\code{value}] either a numeric matrix whose columns give coefficients for
contrasts in the levels of \code{x}, or the (quoted) name of a
function which computes such matrices.
\end{ldescription}
\end{Arguments}
\begin{Details}\relax
If contrasts are not set for a factor the default functions from
\code{\LinkA{options}{options}("contrasts")} are used.

A logical vector \code{x} is converted into a two-level factor with
levels \code{c(FALSE, TRUE)} (regardless of which levels occur in the
variable).

The argument \code{contrasts} is ignored if \code{x} has a matrix
\code{contrasts} attribute set.  Otherwise if \code{contrasts = TRUE}
it is passed to a contrasts function such as
\code{\LinkA{contr.treatment}{contr.treatment}} and if \code{contrasts = FALSE}
an identity matrix is returned.

If \code{value} supplies more than \code{how.many} contrasts, the
first \code{how.many} are used.  If too few are supplied, a suitable
contrast matrix is created by extending \code{value} after ensuring
its columns are contrasts (orthogonal to the constant term) and not
collinear.
\end{Details}
\begin{References}\relax
Chambers, J. M. and Hastie, T. J. (1992)
\emph{Statistical models.}
Chapter 2 of \emph{Statistical Models in S}
eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.
\end{References}
\begin{SeeAlso}\relax
\code{\LinkA{C}{C}},
\code{\LinkA{contr.helmert}{contr.helmert}},
\code{\LinkA{contr.poly}{contr.poly}},
\code{\LinkA{contr.sum}{contr.sum}},
\code{\LinkA{contr.treatment}{contr.treatment}};
\code{\LinkA{glm}{glm}},
\code{\LinkA{aov}{aov}},
\code{\LinkA{lm}{lm}}.
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
utils::example(factor)
fff <- ff[, drop=TRUE]  # reduce to 5 levels.
contrasts(fff) # treatment contrasts by default
contrasts(C(fff, sum))
contrasts(fff, contrasts = FALSE) # the 5x5 identity matrix

contrasts(fff) <- contr.sum(5); contrasts(fff)  # set sum contrasts
contrasts(fff, 2) <- contr.sum(5); contrasts(fff)  # set 2 contrasts
# supply 2 contrasts, compute 2 more to make full set of 4.
contrasts(fff) <- contr.sum(5)[,1:2]; contrasts(fff)
\end{ExampleCode}
\end{Examples}

