How to use mapvalues() method In R Language
The mapvalues() method in the plyr package in R is used to replace the specified values with new values, in the factor vector. The changes are not retained in the original vector.
Syntax: mapvalues(x, from, to)
Arguments :
- x – the factor vector to modify
- from – a vector of the items to replace
- to – a vector of replacement values
R
# importing req libraries library ( "plyr" ) # declare a factor val <- factor ( c ( "Geeks" , "For" , "Geeks" , "Coding" , "Fun" )) # printing the levels of factor variables print ( "Levels of factor" ) lvls <- levels (val) print (lvls) # renaming the factors mapvalues (val, from = c ( "Fun" , "Coding" ), to = c ( "Learning" , "Programming" )) print ( "Modified Levels of factor" ) print ( levels (val)) |
Output:
[1] "Levels of factor" [1] "Coding" "For" "Fun" "Geeks" Geeks For Geeks Programming Learning Levels: [1] "Modified Levels of factor" [1] "Coding" "For" "Fun" "Geeks"
How to Rename Factor Levels in R?
In this article, we are going to how to rename factor levels in R programming language.
A factor variable in R is represented using categorical variables which are represented using various levels. Each unique value is represented using a unique level value. A factor variable or vector in R can be declared using the factor() method.
Syntax: factor(vec)
Arguments : vec – The vector
The unique levels of the factor can be extracted using the levels() method which takes as argument the factor vector created. It displays all the unique entries within the factor variable.
Syntax: levels(fac-vec)
Arguments : fac-vec – The factor vector to extract the values from
Contact Us