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.
In R, we represent categorical or qualitative data with the 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 display labels while keeping the underlying level order:
[1] "Low" "Medium" "High"
[1] 3
[1] TRUE
To reorder, recode or lump rare levels, see the forcats package.
levels() and nlevels() to inspect the categories.levels and ordered = TRUE when categories have a natural order.labels to choose display labels and is.ordered() to check ordering.Next: Lists in R