Replace Value of Data Frame Variable Using dplyr Package in R (Example)
In this R post you’ll learn how to use the dplyr package to change particular values in a data frame column.
The table of content is structured as follows:
Here’s how to do it!
Example Data & Packages
We use the following data as basement for this R tutorial:
data <- data.frame(x1 = c(1, 2, 3, 2, 1, 1, 2), # Create example data x2 = "XX", x3 = 66) data # Print example data # x1 x2 x3 # 1 1 XX 66 # 2 2 XX 66 # 3 3 XX 66 # 4 2 XX 66 # 5 1 XX 66 # 6 1 XX 66 # 7 2 XX 66 |
data <- data.frame(x1 = c(1, 2, 3, 2, 1, 1, 2), # Create example data x2 = "XX", x3 = 66) data # Print example data # x1 x2 x3 # 1 1 XX 66 # 2 2 XX 66 # 3 3 XX 66 # 4 2 XX 66 # 5 1 XX 66 # 6 1 XX 66 # 7 2 XX 66
The previous output of the RStudio console shows the structure of our example data frame: It has seven rows and three columns.
In this R programming language tutorial, we’ll also have to install and load the dplyr package:
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package |
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package
Now, we can use the functions of the dplyr package to modify specific values in our data frame.
Example: Changing Certain Values in Variable Using mutate() & replace() Functions
In this example, I’ll show how to replace particular values in a data frame variable by using the mutate and replace functions in R.
More precisely, the following R code replaces each 2 in the column x1:
data_new <- data %>% # Replacing values mutate(x1 = replace(x1, x1 == 2, 99)) data_new # Print updated data # x1 x2 x3 # 1 1 XX 66 # 2 99 XX 66 # 3 3 XX 66 # 4 99 XX 66 # 5 1 XX 66 # 6 1 XX 66 # 7 99 XX 66 |
data_new <- data %>% # Replacing values mutate(x1 = replace(x1, x1 == 2, 99)) data_new # Print updated data # x1 x2 x3 # 1 1 XX 66 # 2 99 XX 66 # 3 3 XX 66 # 4 99 XX 66 # 5 1 XX 66 # 6 1 XX 66 # 7 99 XX 66
As you can see in the previous output of the RStudio console, each 2 in the variable x1 was replaced by the value 99.
Video & Further Resources
Do you need further information on the R code of this article? Then you may watch the following video of my YouTube channel. In the video, I’m explaining the R programming syntax of this page.
The YouTube video will be added soon.
In addition, you could have a look at some of the other articles on my homepage.
- Replace NA with 0 (10 Examples for Data Frame, Vector & Column)
- Replace Particular Value in Data Frame
- R Programming Overview
Summary: In this R tutorial you learned how to replace values using the dplyr package. Let me know in the comments section, if you have additional questions.
Subscribe to my free statistics newsletter: