Open In App

Reorder Levels of Factor without Changing Order of Values in R

Last Updated : 14 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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,

  • actual_vector is the factor input vector
  • levels are the names to be specified to get in that order. levels parameter can accept the vector elements. Thus the reordering is done manually.

Example: R program to reorder the levels

R




# 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

R




# 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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads