Open In App

Group Factor Levels in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will be looking at the approach to group factor level using the base functions of the R Programming language.

In this approach to group factor levels, the user has to simply call the levels() functions with the required parameters as required by the user, and then it will be leading to the new factor level as specified by the user in other words we will be merging two-factor levels into one category in the R programming language.

Levels() function provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute.

Syntax:

levels(x)

levels(x) <- value

Parameters:

  • x: an object, for example, a factor.
  • value: A valid value for levels(x). For the default method, NULL or a character vector. For the factor method, a vector of character strings with length at least the number of levels of x, or a named list specifying how to rename the levels.

Example: In this example, we will be creating an initial factor of some elements in the string data type and with the help of the levels function, we will be grouping the initial factor levels in the R programming language.

R




gfg <- factor(c("a","b","c","d","c","a"))
gfg
  
gfg1 <- gfg                                 
  
levels(gfg1) <- c("a", "b", "b","b")        
gfg1


Output:

> gfg
[1] a b c d c a
Levels: a b c d
> gfg1
[1] a b b b b a
Levels: a b

Example: In this example, we will be creating an initial factor of some elements in the integer data type and with the help of the levels function, we will be grouping the initial factor levels in the R programming language.

R




gfg <- factor(c(1,2,3,4,5,1,1,3,3,3,3))
gfg
  
gfg1 <- gfg                                 
  
levels(gfg1) <- c(1,5,5,5,5)        
gfg1


Output:

> gfg
 [1] 1 2 3 4 5 1 1 3 3 3 3
Levels: 1 2 3 4 5     
> gfg1  
 [1] 1 5 5 5 5 1 1 5 5 5 5
Levels: 1 5


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