Open In App

How to Reorder Factor Levels in R?

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Creating Data
gfg<-data.frame(x=factor(c('A','B','C','D','E','F','G')),
                y=c(6,8,7,5,3,9,1))
  
# Reordering Levels
gfg$x <- factor(gfg$x, levels=c('G','F','E','C','D','B','A'))
gfg <- gfg[order(levels(gfg$x)),]
  
# Displaying Levels
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




# Creating Data
gfg<-data.frame(x=factor(c('G','F','E','C','D','B','A')),
                y=c(6,8,7,5,3,9,1))
  
# Reordering Levels
gfg$x <- factor(gfg$x, levels=c('A','B','C','D','E','F','G'))
gfg <- gfg[order(levels(gfg$x)),]
  
# Displaying Levels
levels(gfg$x)


Output:

[1] "A" "B" "C" "D" "E" "F" "G"


Last Updated : 19 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads