\HeaderA{levels}{Levels Attributes}{levels}
\methaliasA{levels.default}{levels}{levels.default}
\aliasA{levels<\Rdash}{levels}{levels<.Rdash.}
\methaliasA{levels<\Rdash.factor}{levels}{levels<.Rdash..factor}
\keyword{category}{levels}
\begin{Description}\relax
\code{levels} provides access to the levels attribute of a variable.
The first form returns the value of the levels of its argument
and the second sets the attribute.
\end{Description}
\begin{Usage}
\begin{verbatim}
levels(x)
levels(x) <- value
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{x}] an object, for example a factor.
\item[\code{value}] A valid value for \code{levels(x)}.
For the default method, \code{NULL} or a character vector.  For the
\code{factor} method, a vector of character strings with length at
least the number of levels of \code{x}, or a named list specifying how to
rename the levels.
\end{ldescription}
\end{Arguments}
\begin{Details}\relax
Both the extractor and replacement forms are generic and new methods
can be written for them. The most important method for the replacment
function is that for \code{\LinkA{factor}{factor}}s.

For the factor replacement method, a \code{NA} in \code{value}
causes that level to be removed from the levels and the elements
formerly with that level to be replaced by \code{NA}.

Note that for a factor, replacing the levels via
\code{levels(x) <- value} is not the same as (and is preferred to)
\code{attr(x, "levels") <- value}.

The replacemnt function is \LinkA{primitive}{primitive}, so argument names are
ignored (but this might not be true of its methods).
\end{Details}
\begin{References}\relax
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
\emph{The New S Language}.
Wadsworth \& Brooks/Cole.
\end{References}
\begin{SeeAlso}\relax
\code{\LinkA{nlevels}{nlevels}}, \code{\LinkA{relevel}{relevel}}, \code{\LinkA{reorder}{reorder}}.
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
## assign individual levels
x <- gl(2, 4, 8)
levels(x)[1] <- "low"
levels(x)[2] <- "high"
x

## or as a group
y <- gl(2, 4, 8)
levels(y) <- c("low", "high")
y

## combine some levels
z <- gl(3, 2, 12)
levels(z) <- c("A", "B", "A")
z

## same, using a named list
z <- gl(3, 2, 12)
levels(z) <- list(A=c(1,3), B=2)
z

## we can add levels this way:
f <- factor(c("a","b"))
levels(f) <- c("c", "a", "b")
f

f <- factor(c("a","b"))
levels(f) <- list(C="C", A="a", B="b")
f
\end{ExampleCode}
\end{Examples}

