\Header{factor}{Factors}
\alias{ordered}{factor}
\alias{is.factor}{factor}
\alias{is.ordered}{factor}
\alias{as.factor}{factor}
\alias{as.ordered}{factor}
\keyword{category}{factor}
\keyword{NA}{factor}
\begin{Usage}
\begin{verbatim}
factor(x, levels = sort(unique(x), na.last = TRUE), labels,
       exclude = NA, ordered = FALSE)
ordered(x, levels = sort(unique(x), na.last = TRUE), labels,
       exclude = NA, ordered = TRUE)

is.factor(x)
is.ordered(x)

as.factor(x)
as.ordered(x)
\end{verbatim}
\end{Usage}
\begin{Value}
The function \texttt{factor} is used to encode a vector as a factor (the
names category and enumerated type are also used for factors).  If
\texttt{ordered} is \texttt{TRUE}, the factor levels are assumed ordered.
By default the levels are unordered.  For compatibility purposes,
there is also a function called \texttt{ordered} which provides an
alternative way of creating ordered factors.

The encoding of the vector happens as follows: if \texttt{x[i]} equals
\texttt{levels[j]}, then the \texttt{i}-th element of the result is
\texttt{j}.  If no match is found for \texttt{x[i]} in \texttt{levels}, then
the \texttt{i}-th element of the result is set to \texttt{\Link{NA}}.  Any
values listed in \texttt{exclude} result in \texttt{NA}s appearing in the
factor returned.  If \texttt{exclude} is set to a zero length vector,
then any \texttt{\Link{NA}} values in \texttt{x} are used for form a new
level for the factor.  \emph{This means that there will be no
\texttt{NA} values in the result}.

\texttt{factor} applied to a factor is a no-op, except if there are
empty levels. In that case, a factor with the reduced level set
set is returned.

\texttt{labels} is a vector of character strings used to label the
levels of the factor.  The default is to use the encoded factor levels.

\texttt{is.factor} returns \texttt{TRUE} or \texttt{FALSE} depending on
whether its argument is of type factor or not.  Correspondingly,
\texttt{is.ordered} returns \texttt{TRUE} when its
argument is ordered and \texttt{FALSE} otherwise.

\texttt{as.factor} coerces its argument to a factor.
It is an abbreviated form of \texttt{factor}.

\texttt{as.ordered(x)} returns \texttt{x} if this is ordered, and
\texttt{ordered(x)} otherwise.\end{Value}
\begin{SeeAlso}
\texttt{\Link{gl}} for construction of ``balanced'' factors and
\texttt{\Link{C}} for factors with specified contrasts.
\texttt{\Link{levels}} and \texttt{\Link{nlevels}} for accessing the
levels,  and \texttt{\Link{codes}} to get integer codes.\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
ff <- factor(substring("statistics",1:10,1:10), levels=letters)
ff
codes(ff)
factor(ff)# drops levels that don't occur !
factor(factor(letters[7:10])[2:3]) # excercise indexing and reduction
\end{ExampleCode}
\end{Examples}

