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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

[1] female male   male   female
Levels: female male
[1] abc def def abc
Levels: abc def
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.