R Ordered Factors
ordered() builds a factor whose levels have a real order. The order runs from the first level to the last level in the list.
Build an ordered factor
ordered() builds the values with the levels low, mid and high. The print joins the levels with < signs to show the order.
sizes <- ordered(c("low", "high", "mid"), levels = c("low", "mid", "high"))
print(sizes)Sort and smallest
min() gives low because low is the first level. sort() arranges the same values from low up to high.
sizes <- ordered(c("high", "low", "mid"), levels = c("low", "mid", "high"))
print(min(sizes))
print(sort(sizes))Compare two values
The first value is low and the second value is high. The < test gives TRUE one way and FALSE the other way.
sizes <- ordered(c("low", "high"), levels = c("low", "mid", "high"))
print(sizes[1] < sizes[2])
print(sizes[2] < sizes[1])Example
ratings <- ordered(c("mid", "low", "high", "mid"), levels = c("low", "mid", "high"))
print(sort(ratings))
print(min(ratings))
print(max(ratings))Key points
- ordered() takes the values and a levels list written in order.
- A printed ordered factor joins its levels with < signs.
- min() returns the smallest value by level order.
- sort() arranges values by level order.
- Two ordered values can be compared with < and the test gives TRUE or FALSE.
- A plain factor refuses a < test between its values.
In this example sort() arranges the ratings by level order, with low first and high last. min() gives low and max() gives high, both by the same level order.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
An ordered factor has levels low, mid and high and holds the values high, low and mid. What does min() give?