In this article, we will be looking at the approach to reorder factor levels using functions in R Programming language.
Using factor() function to reorder factor levels is the simplest way to reorder the levels of the factors, as here the user needs to call the factor function with the factor level stored and the sequence of the new levels which is needed to replace from the previous factor levels as the functions parameters and this process will be leading to the reordering of the factor levels as specified by the user in the argument of the function.
Factor() function is used to encode a vector as a factor.
Syntax: factor(x = character(), levels)
Parameters:
- x: a vector of data, usually taking a small number of distinct values.
- levels: an optional vector of the unique valuesthat x might have taken.
Example1: Reorder Factor Levels
Initial levels :
[1] "A" "B" "C" "D" "E" "F" "G"
R
gfg<- data.frame (x= factor ( c ( 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' )),
y= c (6,8,7,5,3,9,1))
gfg$x <- factor (gfg$x, levels= c ( 'G' , 'F' , 'E' , 'C' , 'D' , 'B' , 'A' ))
gfg <- gfg[ order ( levels (gfg$x)),]
levels (gfg$x)
|
Output:
[1] "G" "F" "E" "C" "D" "B" "A"
Example 2: Reorder Factor Levels
Initial levels:
'G','F','E','C','D','B','A'
R
gfg<- data.frame (x= factor ( c ( 'G' , 'F' , 'E' , 'C' , 'D' , 'B' , 'A' )),
y= c (6,8,7,5,3,9,1))
gfg$x <- factor (gfg$x, levels= c ( 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' ))
gfg <- gfg[ order ( levels (gfg$x)),]
levels (gfg$x)
|
Output:
[1] "A" "B" "C" "D" "E" "F" "G"
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Dec, 2021
Like Article
Save Article