Open In App

Get or Set Levels of a Factor in R Programming – levels() Function

Improve
Improve
Like Article
Like
Save
Share
Report

levels() function in R Language is used to get or set the levels of a factor.

Syntax: levels(x)

Parameters:
x: Factor Object

Example 1:




# R program to get levels of a factor
  
# Creating a factor
gender <- factor(c("female", "male", "male", "female")); 
gender
  
# Calling levels() function
# to get the levels
levels(gender)


Output:

[1] female male   male   female
Levels: female male
[1] "female" "male"  

Example 2:




# R program to set levels of a factor
  
# Creating a factor
gender <- factor(c("female", "male", "male", "female")); 
gender
  
# Calling levels() function
# to set the levels
levels(gender) <- c("abc", "def")
gender


Output:

[1] female male   male   female
Levels: female male
[1] abc def def abc
Levels: abc def

Last Updated : 16 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads