Factors

Usage

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, ordered = FALSE)
as.ordered(x)

Value

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

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

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.

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

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

as.factor coerces its argument to a factor. It is an abbreviated form of factor.

as.ordered(x) returns x if this is ordered, and ordered(x) otherwise.

See Also

gl for construction of ``balanced'' factors; levels and nlevels for accessing the levels, and codes to get integer codes.

Examples

ff <- factor(substring("statistics",1:10,1:10), levels=letters)
ff
codes(ff)
factor(ff)
factor(factor(letters[7:10])[2:3]) # excercise indexing and reduction


[Package Contents]