Open In App

Reorder Levels of Factor without Changing Order of Values in R

In this article, we will discuss how to Reorder Levels of Factor without Changing the Order of Values in R programming language.

If we want to change the order of the levels, we can specify the levels() parameter in the factor() function



Syntax:

factor(actual_vector,levels)



Where,

Example: R program to reorder the levels




# create a student names vector
student= factor(c("sravan","bobby","ojaswi",
                  "rohith","gnanesh"))
  
# display
print(student)
  
# change the order levels
changed = factor(student, c("bobby", "sravan"
                            "ojaswi", "gnanesh",
                            "rohith"))
  
# display
print(changed)

Output:

[1] sravan  bobby   ojaswi  rohith  gnanesh

Levels: bobby gnanesh ojaswi rohith sravan

[1] sravan  bobby   ojaswi  rohith  gnanesh

Levels: bobby sravan ojaswi gnanesh rohith

Example: R program to reorder the levels




# create a student names vector
student= factor(c("sravan","bobby","ojaswi",
                  "rohith","gnanesh"))
  
# display
print(student)
  
# change the order levels
changed = factor(student, c("sravan", "ojaswi", "bobby",
                            "gnanesh","rohith"))
  
# display
print(changed)

Output:

[1] sravan  bobby   ojaswi  rohith  gnanesh

Levels: bobby gnanesh ojaswi rohith sravan

[1] sravan  bobby   ojaswi  rohith  gnanesh

Levels: sravan ojaswi bobby gnanesh rohith


Article Tags :