To access factor levels in R, you can use the levels()
function. This function returns a vector of the levels of a factor. Accessing factor levels is useful when you need to inspect, modify, or use the levels in further analysis.
In this example,
fruits
which contains the values 'apple'
, 'banana'
, 'cherry'
, and 'apple'
. This vector represents categorical data.factor()
function to convert the fruits
vector into a factor. We assign the result to a variable named fruits_factor
. The factor()
function automatically identifies the unique levels of the vector.levels()
function to access the levels of the fruits_factor
. The levels()
function returns a vector of the unique levels in the factor.fruits_factor
to the console to see the distinct categories within the factor. This allows us to inspect the factor levels for further analysis.fruits <- c('apple', 'banana', 'cherry', 'apple')
fruits_factor <- factor(fruits)
levels_fruits <- levels(fruits_factor)
print(levels_fruits)
[1] "apple" "banana" "cherry"
In this example,
grades
which contains the values 85
, 90
, 75
, and 85
. This vector represents categorical data in numerical form.factor()
function to convert the grades
vector into a factor. We assign the result to a variable named grades_factor
. The factor()
function automatically identifies the unique levels of the vector.levels()
function to access the levels of the grades_factor
. The levels()
function returns a vector of the unique levels in the factor.grades_factor
to the console to see the distinct categories within the factor. This allows us to inspect the factor levels for further analysis.grades <- c(85, 90, 75, 85)
grades_factor <- factor(grades)
levels_grades <- levels(grades_factor)
print(levels_grades)
[1] "75" "85" "90"
In this example,
responses
which contains the values TRUE
, FALSE
, TRUE
, and TRUE
. This vector represents categorical data in logical form.factor()
function to convert the responses
vector into a factor. We assign the result to a variable named responses_factor
. The factor()
function automatically identifies the unique levels of the vector.levels()
function to access the levels of the responses_factor
. The levels()
function returns a vector of the unique levels in the factor.responses_factor
to the console to see the distinct categories within the factor. This allows us to inspect the factor levels for further analysis.responses <- c(TRUE, FALSE, TRUE, TRUE)
responses_factor <- factor(responses)
levels_responses <- levels(responses_factor)
print(levels_responses)
[1] "FALSE" "TRUE"
In this tutorial, we learned How to Access Factor Levels in R language with well detailed examples.