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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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"))

chevron_right


Output:

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

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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"))

chevron_right


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 Posts:


Blockchain Enthusiast

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.