Section 4 Factor: Categorical

4.1 Categorical Factor

Example vector: x <- rep(c('L','M','H'), length=30)

Function Explanation Example
factor Make a vector to factor factor(x=x, levels=c(L,M,H), labels=c(Low,Med,High))
as.factor Convert a vector to factor as.factor(x)
ordered Make a vector to an ordered factor ordered(x=x, levels=c(L,M,H), labels=c(Low,Med,High))
as.ordered Convert a vector to ordered factor as.ordered(x)
levels Get the labels of the factor levels levels(x)
nlevels Get the number of levels of a factor nlevels(x)

Note: In the above table, levels and labels of a factor should be with single or double quotes.


4.2 Example

x <- rep(c('L','M','H'), length=30)

f1x <- as.factor(x)
x
f1x
levels(f1x)
nlevels(f1x)
as.numeric(f1x)
table(f1x)
attributes(f1x)

f2x <- factor(x=x, levels=c('L','M','H'), labels=c('Low','Med','High'))
x
f2x
levels(f2x)
nlevels(f2x)
as.numeric(f2x)
table(f2x)
attributes(f2x)

Note: The order of the label is important