R Factors
A factor stores categorical data: values that come from a fixed set of categories, such as blood type, a size (S/M/L) or a country. Internally a factor is a vector of integer codes plus a set of labels called levels.
sizes <- factor(c("M", "S", "L", "M", "M", "S"))
sizes
levels(sizes)
nlevels(sizes)
as.integer(sizes)[1] M S L M M S
Levels: L M S
[1] "L" "M" "S"
[1] 3
[1] 2 3 1 2 2 3
By default the levels are sorted alphabetically, which is why L comes before M and S. The integer codes refer to positions in levels().
Why factors?
- Statistical functions (
table(),lm(),boxplot(),aggregate()) treat factors as groups. - Levels define every possible category, even ones that don't occur in the data.
- You control the order of categories in tables and plots.
answers <- factor(c("yes", "no", "yes", "yes"), levels = c("yes", "no", "maybe"))
table(answers)
summary(answers)answers
yes no maybe
3 1 0
yes no maybe
3 1 0
maybe appears with a count of 0 because it is a level, even though nobody answered it.
Setting the order of levels
Give the levels argument to choose the order. For categories that have a natural ranking, create an ordered factor, which also allows comparisons:
shirt <- factor(c("M", "S", "L", "M", "XL"),
levels = c("S", "M", "L", "XL"), ordered = TRUE)
shirt
shirt[shirt > "M"]
max(shirt)
sort(shirt)[1] M S L M XL
Levels: S < M < L < XL
[1] L XL
Levels: S < M < L < XL
[1] XL
Levels: S < M < L < XL
[1] S M M L XL
Levels: S < M < L < XL
Changing levels
Assign to levels() to rename categories. Values outside the levels become NA with a warning, so you can't silently add a category by assignment:
pet <- factor(c("c", "d", "c", "b"))
levels(pet) <- c("bird", "cat", "dog")
pet
pet[2] <- "fish"
pet[1] cat dog cat bird
Levels: bird cat dog
Warning message:
In `[<-.factor`(`*tmp*`, 2, value = "fish") : invalid factor level, NA generated
[1] cat <NA> cat bird
Levels: bird cat dog
Use droplevels() to remove unused levels after filtering, and factor(x, levels = ...) to add new ones.
Factors in data frames
Many built-in datasets use factors. iris$Species and ToothGrowth$supp are factors, and functions like tapply() use them to split data into groups:
class(iris$Species)
levels(iris$Species)
tapply(iris$Petal.Length, iris$Species, mean)[1] "factor"
[1] "setosa" "versicolor" "virginica"
setosa versicolor virginica
1.462 4.260 5.552
Converting numbers to categories with cut()
cut() turns a numeric vector into a factor by putting values into intervals:
ages <- c(4, 17, 25, 42, 67, 13, 80)
groups <- cut(ages, breaks = c(0, 12, 19, 64, Inf),
labels = c("child", "teen", "adult", "senior"))
groups
table(groups)[1] child teen adult adult senior teen senior
Levels: child teen adult senior
groups
child teen adult senior
1 2 2 2
Note: Converting a factor that looks like numbers back to numbers needs care:
as.numeric(f)gives the internal codes. Useas.numeric(as.character(f))instead.
Test yourself
What are the default levels of factor(c("b", "c", "a", "b"))?
- b c a
- a b c
- b c a b
- 1 2 3
What does as.integer(factor(c("10", "5", "10"))) return?
- 10 5 10
- 1 2 1
- 2 1 2
- NA
Which argument makes factor levels comparable with < and >?
- sorted = TRUE
- ordered = TRUE
- rank = TRUE
- compare = TRUE