In this tutorial, we will learn about factors in R. We will cover the basics of creating, accessing, modifying, and performing operations on factors.
A factor in R is used to represent categorical data. Factors are stored as integer vectors with a corresponding set of character values to use when the factor is displayed. They are useful in statistical modeling where categorical variables are required.
Factors can be created in R using the factor()
function:
data <- c("high", "medium", "low", "medium")
levels <- c("low", "medium", "high")
factor_data <- factor(data, levels = levels)
Factors ensure that the levels are in a specific order.
factor()
function.data <- c("high", "medium", "low", "medium")
levels <- c("low", "medium", "high")
factor_data <- factor(data, levels = levels)
print(factor_data)
[1] high medium low medium Levels: low medium high
levels()
function to access the levels of the factor.data <- c("high", "medium", "low", "medium")
levels <- c("low", "medium", "high")
factor_data <- factor(data, levels = levels)
print(levels(factor_data))
[1] "low" "medium" "high"
levels()
function.data <- c("high", "medium", "low", "medium")
levels <- c("low", "medium", "high")
factor_data <- factor(data, levels = levels)
levels(factor_data) <- c("L", "M", "H")
print(factor_data)
[1] H M L M Levels: L M H
data <- factor(c("yes", "no", "yes", "no"), levels = c("no", "yes"))
if ("yes" %in% levels(data)) {
print("Yes is a level")
} else {
print("Yes is not a level")
}
Yes is a level
data <- factor(c("apple", "banana", "cherry", "apple"), levels = c("apple", "banana", "cherry"))
if ("apple" %in% levels(data)) {
print("Factor contains apple")
} else {
print("Factor does not contain apple")
}
Factor contains apple
numbers <- factor(c(2, 3, 4, 5), levels = c(2, 3, 4, 5))
if (4 %% 2 == 0) {
print("4 is even")
} else {
print("4 is odd")
}
4 is even