Reorder Levels of Factor without Changing Order of Values in R
Last Updated :
14 Sep, 2021
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
student= factor ( c ( "sravan" , "bobby" , "ojaswi" ,
"rohith" , "gnanesh" ))
print (student)
changed = factor (student, c ( "bobby" , "sravan" ,
"ojaswi" , "gnanesh" ,
"rohith" ))
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
student= factor ( c ( "sravan" , "bobby" , "ojaswi" ,
"rohith" , "gnanesh" ))
print (student)
changed = factor (student, c ( "sravan" , "ojaswi" , "bobby" ,
"gnanesh" , "rohith" ))
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
Please Login to comment...