Factors
Table of Contents
- Overview
as.factor(x)- Reorder factor elements
- Put classes with 0 count in
table() - Drop unused levels from factors
Overview
- R provides both ordered and unordered factors.
sz <- c("M", "L", "S", "XL")
sz1 <- factor(sz) # Levels are sorted by alphabetical order by default
sz1
sz2 <- factor(sz, levels = c("S", "M", "L", "XL"))
sz2
sz3 <- factor(sz, ordered = FALSE)
sz3
levels(sz1)
levels(sz2)
table(sz2) # a contingency table of the counts[1] M L S XL
Levels: L M S XL
[1] M L S XL
Levels: S M L XL
[1] M L S XL
Levels: L M S XL
[1] "L" "M" "S" "XL"
[1] "S" "M" "L" "XL"
sz2
S M L XL
1 1 1 1
as.factor(x) reference
as.factorcoerces its argument to afactor. It is an abbreviated (sometimes faster) form of factor.
Reorder factor elements howto
> mydata$Treatment
[1] L M H L M H
Levels: H L M
> as.integer(mydata$Treatment)
[1] 2 3 1 2 3 1
> factor(mydata$Treatment,c("L","M","H"))
[1] L M H L M H # <-- not changed
Levels: L M H # <-- changed
> as.integer(factor(mydata$Treatment,c("L","M","H")))
[1] 1 2 3 1 2 3 # <-- changedPut classes with 0 count in table() howto
x
1 2 5
3 3 3
To put 3 and 4 as columns:
fx
1 2 3 4 5
3 3 0 0 3
Drop unused levels from factors howto
[1] apple banana orange
Levels: apple banana orange
Note that
Levels wasn't changed, even though x[1] contains only apple
[1] apple
Levels: apple banana orange
Put
drop = TRUE
[1] apple
Levels: apple
Also, you can use
droplevels as follows:
[1] apple
Levels: apple