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.
args(factor)function (x = character(), levels, labels = levels, exclude = NA,
ordered = is.ordered(x), nmax = NA)
NULL
devices <- factor(c('Mobile', 'Tablet', 'Desktop'))
devices[1] Mobile Tablet Desktop
Levels: Desktop Mobile Tablet
# number of levels
nlevels(devices)[1] 3
# levels
levels(devices)[1] "Desktop" "Mobile" "Tablet"
Use the levels argument together with ordered = TRUE when the categories have a natural order:
size <- factor(c('Medium', 'Low', 'High', 'Low', 'Medium'),
levels = c('Low', 'Medium', 'High'), ordered = TRUE)
size[1] Medium Low High Low Medium
Levels: Low < Medium < High
levels(size)[1] "Low" "Medium" "High"
Use the labels argument to attach shorter or prettier display labels while keeping the underlying level order:
size_labeled <- factor(c('Low', 'Medium', 'High'),
levels = c('Low', 'Medium', 'High'), labels = c('L', 'M', 'H'))
size_labeled[1] L M H
Levels: L M H
# existing levels
levels(size)[1] "Low" "Medium" "High"
# number of levels
nlevels(size)[1] 3
# is this an ordered factor?
is.ordered(size)[1] TRUE
For modern factor manipulation (reordering, recoding, lumping rare levels), see the forcats package.