Skip to content
Related Articles

Related Articles

Improve Article

Replace values of a Factor in R Programming – recode_factor() Function

  • Last Updated : 01 Jun, 2020

Factors in R programming are kind of data structures that stores categorical data i.e., levels and can have any type of data (integer, string, etc). recode_factor() function in R Language is used to replace certain values in a factor. To use recode_factor() function, dplyr package is required.

Syntax:
recode_factor(x, …, .ordered = TRUE)

Parameters:
x: represents factor object of a vector
… :represents replacements
.ordered: creates an ordered factor if TRUE.

Example 1:




# Required for recode_factor() function
install.packages("dplyr")
  
# Loading package
library(dplyr)
  
# Create factor object
f <- as.factor(c("a", "b", "c"))
  
# Print factor object
cat("Before replacement:\n")
print(f)
  
# Replacing single value
cat("After replacement:\n")
print(recode_factor(f, "a" = "x"))

Output:

Before replacement:
[1] a b c
Levels: a b c

After replacement:
[1] x b c
Levels: x b c

Example 2:




# Required for recode_factor() function
install.packages("dplyr")
  
# Loading package
library(dplyr)
  
# Create factor object
f <- as.factor(c("a", "b", "c"))
  
# Print factor object
cat("Before replacement:\n")
print(f)
  
# Replacing multiple values
cat("After replacement:\n")
print(recode_factor(f, "a" = "x", "b" = "y"))

Output:

Before replacement:
[1] a b c
Levels: a b c

After replacement:
[1] x y c
Levels: x y c



My Personal Notes arrow_drop_up
Recommended Articles
Page :