args(factor)function (x = character(), levels, labels = levels, exclude = NA,
ordered = is.ordered(x), nmax = NA)
NULL
Learning Objectives: After this chapter you will be able to:
- Create a factor from a character vector.
- Inspect and count levels with
levels()andnlevels().- Impose a natural order with
levels=together withordered = TRUE.- Attach shorter display labels with
labels=.- Test for ordering with
is.ordered().- Reach for
forcatswhen you need to recode, reorder, or lump levels.
Categorical or qualitative data in R is treated as data type factor.
function (x = character(), levels, labels = levels, exclude = NA,
ordered = is.ordered(x), nmax = NA)
NULL
Use the levels argument together with ordered = TRUE when the categories have a natural order:
Use the labels argument to attach shorter or prettier display labels while keeping the underlying level order:
[1] "Low" "Medium" "High"
[1] 3
[1] TRUE
For modern factor manipulation (reordering, recoding, lumping rare levels), see the forcats package.