R Change Values in Column of Data Frame Using dplyr Package (Example Code)
This article explains how to replace values using the dplyr package in the R programming language.
Preparing the Example
data(iris) # Loading example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
install.packages("dplyr") # Install & load dplyr library("dplyr") |
install.packages("dplyr") # Install & load dplyr library("dplyr")
Example: Apply mutate & replace Functions to Replace Particular Values in Data Frame Column
iris_new <- iris %>% # Modify values in data frame column mutate(Petal.Width = replace(Petal.Width, Petal.Width == 0.2, 5555)) head(iris_new) # Show head of updated iris data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 5555.0 setosa # 2 4.9 3.0 1.4 5555.0 setosa # 3 4.7 3.2 1.3 5555.0 setosa # 4 4.6 3.1 1.5 5555.0 setosa # 5 5.0 3.6 1.4 5555.0 setosa # 6 5.4 3.9 1.7 0.4 setosa |
iris_new <- iris %>% # Modify values in data frame column mutate(Petal.Width = replace(Petal.Width, Petal.Width == 0.2, 5555)) head(iris_new) # Show head of updated iris data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 5555.0 setosa # 2 4.9 3.0 1.4 5555.0 setosa # 3 4.7 3.2 1.3 5555.0 setosa # 4 4.6 3.1 1.5 5555.0 setosa # 5 5.0 3.6 1.4 5555.0 setosa # 6 5.4 3.9 1.7 0.4 setosa
Related Articles
Have a look at the following R programming tutorials. They explain similar topics as this post.