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:
install.packages( "dplyr" )
library(dplyr)
f < - as.factor(c( "a" , "b" , "c" ))
cat( "Before replacement:\n" )
print (f)
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:
install.packages( "dplyr" )
library(dplyr)
f < - as.factor(c( "a" , "b" , "c" ))
cat( "Before replacement:\n" )
print (f)
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
Last Updated :
01 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...