Converting Variables into Factors

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():

(animals <- sample(c("dog", "cat", "mongoose"), 25, TRUE))
 [1] "mongoose" "mongoose" "dog"      "dog"      "dog"      "mongoose"
 [7] "dog"      "dog"      "cat"      "mongoose" "cat"      "mongoose"
[13] "cat"      "mongoose" "dog"      "cat"      "dog"      "dog"     
[19] "cat"      "dog"      "mongoose" "dog"      "dog"      "mongoose"
[25] "dog"     
(animalsF <- as.factor(animals))
 [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:

bfi0 <- bfi
bfi$gender <- factor(bfi$gender, labels = c("male", "female"))
levels(bfi$gender)
[1] "male"   "female"
table(numeric = bfi0$gender, factor = bfi$gender)
       factor
numeric male female
      1  919      0
      2    0   1881

This approach ensures that numeric codes are mapped to descriptive category names.

Back to top