recode & recode_factor R Functions of dplyr Package (2 Examples)

 

In this article you’ll learn how to replace certain values with the recode and recode_factor functions of the dplyr package in R.

The article looks as follows:

Let’s take a look at some R codes in action:

 

Example 1: recode Function

Before we can apply the recode function, we need to install and load the dplyr package to RStudio:

install.packages("dplyr")                     # Install & load dplyr
library("dplyr")

Furthermore, we need to create an example vector in R:

x_num <- c(4, 3, 1, 5, 2, 3, 3)               # Create example vector
x_num                                         # Print example vector
# 4 3 1 5 2 3 3

Our example vector is a numeric vector containing six elements.

Let’s assume that we want to replace the value 3 by the value 99. Then, we can apply the recode function as shown below:

recode(x_num, "3" = 99)                       # Apply recode function
# 4 99  1  5  2 99 99

 

Example 2: recode_factor Function

It is also possible to replace values of a factor variable. First, we have to create an example factor:

x_fac <- as.factor(c("aa", "bb", "aa", "cc")) # Create factor vector
x_fac                                         # Print factor vector
# [1] aa bb aa cc
# Levels: aa bb cc

Now, let’s assume that we want to replace the factor level aa by the new factor level xxx. Then, we can use the recode_factor function as follows:

recode_factor(x_fac, "aa" = "xxx")            # Apply recode_factor function
# [1] xxx bb  xxx cc 
# Levels: xxx bb cc

Note that that recode_factor function does not only replace the values, it also removes the old factor level and creates a new factor level.

 

Video & Further Resources

Do you want to learn more about recoding data with the dplyr package in R? Then you may want to watch the following video of my YouTube channel. In the video, I’m illustrating some further R programming code for functions of the dplyr package:

 

 

Additionally, you might read the other articles of my website.

 

At this point you should have learned how to recode values of column variables and vectors with dplyr in the R programming language. Let me know in the comments, if you have additional questions.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top