Factors

Table of Contents

Overview

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

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  # <-- changed

Put classes with 0 count in table() howto

x <- c(1,1,1,2,2,2,5,5,5)
table(x)
x
1 2 5 
3 3 3

To put 3 and 4 as columns:

fx <- factor(x, levels = min(x):max(x))
table(fx)
fx
1 2 3 4 5 
3 3 0 0 3

Drop unused levels from factors howto

x <- factor(c("apple", "banana", "orange"))
x
[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