Introduction to Factors in R. Factors play a crucial role in data... | by Linda Ngo | Towards Data Science

A factor refers to a statistical data type used to store categorical variables. Categorical variables belong to a limited number of categories. Continuous variables, on the other hand, can correspond to an infinite number of values.
It is important to distinguish whether you are working with a categorical variable or a continuous variable, as statistical models treat both types differently.
An example of a categorical variable is sex. In most cases, you can limit the categories to “Male” or “Female”. While there may be circumstances where you may include additional categories (whether to take into consideration chromosomal variation, hermaphroditic animals, or different cultural norms), you will always have a finite number of categories.
To create factors in R, use the factor() function. The factor function is used to encode a vector as a factor (other terms for factors are ‘category’ and ‘enumerated type’). For example, sex_vector contains the sex of 5 different individuals:
sex_vector <- c("Male", "Female", "Female", "Male", "Male")
It is clear that there are two categories (factor levels): “Male” and “Female”.
The function factor() will encode the vector as a factor:
factor_sex_vector <- factor(sex_vector)
There are two different types of categorical variables:
A nominal categorical variable, which is a categorical variable without an implied order. It is impossible to say that ‘one is worth more than the other.’ For example, consider the categories "Elephant" , "Giraffe" , "Donkey" , and "Horse" . It is impossible to say that one stands above or below the other.
An ordinal categorical variable, which has a natural ordering. Consider the categories: "Low" , "Medium" , and"High" . It is obvious that "Medium" ranks higher than "Low" , and "High" ranks above "Medium" .
R constructs and prints nominal and ordinal variables differently. For nominal variables, there is no ordering, so R prints them without indicating any ordering.
# Animals[1] Elephant Giraffe  Donkey   Horse   Levels: Donkey Elephant Giraffe Horse
For ordinal variables, R indicates order using < .
# Temperature[1] High   Low    High   Low    MediumLevels: Low < Medium < High
Sometimes, it can be helpful to change the names of specific factor levels in a data set for clarity or other reasons. You can do this using the levels() function:
levels(factor_vector) <- c("name1", "name2", ...)
For example, suppose the raw data from a survey contains the a question regarding the sex of the respondent and just two categories were recorded: "M" and "F" .
survey_vector <- c("M", "F", "F", "M", "M")
Recording the sex with abbreviations can be convenient while collecting data (especially with pen and paper), but it can become confusing once it is time to analyze the data. At that point, you may want to change the factor levels to "Male" and "Female" instead of "M" and "F" for clarity.
Caution: the order with which you assign the levels is important. levels(factor_survey_vector) outputs [1] "F" "M" . If you don’t specify the levels of the factor when you are creating a vector, R will automatically assign them alphabetically. To correctly map "F" to "Female" and "M" to "Male" , the levels should be set to c("Female", "Male") , in this order.
The summary() function gives a quick overview of the contents of a variable:
summary(my_var)
Suppose we want to determine how many responses of each factor level we have in our vector. We can use the summary() function to determine this.
What happens when you try to compare elements of a factor? In factor_survey_vector you have a factor with two levels: "Male" and "Female" . But how are these valued relative to each other?
Let’s test if male is greater than ( > ) female .
For unordered (or nominal) factor levels, such as "Male" and "Female" , comparison operators, such as the greater than operator, are not meaningful and R returns a warning message to reflect that.
R attaches an equal value to the levels for factors by default. However, this does not necessarily have to be the case. Sometimes you will also deal with factors that have a natural ordering between its categories. Such factors are called ordinal factors. In this circumstance, we must pass this information to R.
Suppose you want to evaluate the performance five analysts. To do this, you track their speed as either "slow" , "medium" , or "fast" . You get the following results:
Analyst 1 is medium,
Analyst 2 is slow,
Analyst 3 is slow,
Analyst 4 is medium, and
Analyst 5 is fast.
Our first step is the construct a vector with five entries and assign the speed factor to each analyst.
# Create speed_vectorspeed_vector <- c("medium", "slow", "slow", "medium", "fast")
The speed_vector should be converted to an ordinal factor since its categories have a natural ordering. That is, "fast" is greater than "medium" , which is then greater than "slow" .
By default, the factor() function transforms the speed_vector into an unordered factor. To create an ordered factor, two additional arguments are needed: ordered and levels .
factor(some_vector, ordered = TRUE, levels = c("lev1", "lev2", ...))
By setting the argument ordered to TRUE , you indicate that the factor is ordered. With the argument levels you give the values of the factor in the correct order.
Create an ordered vector from the speed vector. The correct ordering of the factor is c("slow", "medium", "fast") .
# Create speed_vectorspeed_vector <- c("medium", "slow", "slow", "medium", "fast")# Convert speed_vector to ordered factor vectorfactor_speed_vector <- factor(speed_vector, ordered=TRUE, levels=c("slow", "medium", "fast"))# Print factor_speed_vectorfactor_speed_vectorsummary(factor_speed_vector)
You can compare different elements of an ordered factor by using the well-known operators. For example, to compare if the the element of the first factor vector is greater than the first element of the second factor vector, you would use the greater than operator ( > ).
factor_vector1[1] > factor_vector2[1]
Suppose ‘data analyst number two’ complains that ‘data analyst number five’ is slowing down the entire project. Check if their statement is true.
# Create factor_speed_vectorspeed_vector <- c("medium", "slow", "slow", "medium", "fast")factor_speed_vector <- factor(speed_vector, ordered = TRUE, levels = c("slow", "medium", "fast"))# Factor value for second data analystda2 <- factor_speed_vector[2]# Factor value for fifth data analystda5 <- factor_speed_vector[5]# Is data analyst 2 faster than data analyst 5?da2 > da5
All images, unless specified, are owned by the author. The banner image was created using Canva.