R Factors
A factor stores values that come from a fixed set of labels. Those labels are called levels.
Make a factor
factor turns the labels into a factor with three levels. The levels print in alphabetical order below the values.
f <- factor(c("low", "high", "low", "mid"))
print(f)Levels and one item
levels prints the labels as a character vector. The first item prints with the levels listed below it.
f <- factor(c("low", "high", "low", "mid"))
print(levels(f))
print(f[1])Set your own level order
The levels argument fixes the order as low, mid and high. The values stay the same and only the level order changes.
f <- factor(c("low", "high", "low", "mid"), levels = c("low", "mid", "high"))
print(f)Example
sizes <- factor(c("small", "large", "small", "medium"), levels = c("small", "medium", "large"))
print(sizes)
print(levels(sizes))Key points
- factor() turns a vector into a factor.
- The levels are the allowed labels for the values.
- Levels appear in alphabetical order by default.
- The levels argument sets your own order for the labels.
- levels() prints the labels as a character vector.
In this example, the levels argument fixes the order as small, medium and large. levels then prints that same order as a vector.
Note
summary() counts the values in each level and its code arrives in the next category.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What are the levels of factor(c("low", "high", "low", "mid")) in order?