A common transformation involves converting numeric or character variables into factors—categorical variables that have defined levels. Factors are essential for statistical modeling and for treating variables like gender, education level, or species as discrete categories rather than continuous quantities.
We can create a simple character vector and convert it into a factor using as.factor():
[1] mongoose mongoose dog dog dog mongoose dog dog
[9] cat mongoose cat mongoose cat mongoose dog cat
[17] dog dog cat dog mongoose dog dog mongoose
[25] dog
Levels: cat dog mongoose
levels(animalsF)
[1] "cat" "dog" "mongoose"
table(character = animals, factor = animalsF)
factor
character cat dog mongoose
cat 5 0 0
dog 0 12 0
mongoose 0 0 8
For character vectors, this quick-and-dirty approach works well. However, it’s less informative when applied to numeric variables because it treats numbers as labels rather than meaningful values:
genderF <-as.factor(bfi$gender)levels(genderF)
[1] "1" "2"
table(numeric = bfi$gender, factor = genderF)
factor
numeric 1 2
1 919 0
2 0 1881
To explicitly control the factor levels and their labels, use the factor() function: