Change Certain Value in Data Frame to Different Values in R (Example)

On this page you’ll learn how to replace particular values in a data frame to different values in R.

Example Data

my_df <- data.frame(x = c("a", "a", "a", "b", "b", "b"),      # Create example data
                    y = c("a", "b", "a", "b", "a", "b"),
                    stringsAsFactors = FALSE)
my_df                                                         # Return data to console
#   x y
# 1 a a
# 2 a b
# 3 a a
# 4 b b
# 5 b a
# 6 b b

Replace Value in Data Frame in R

my_df[my_df == "a"] <- "new"                                  # Replace values
my_df                                                         # Return data to console
#     x   y
# 1 new new
# 2 new   b
# 3 new new
# 4   b   b
# 5   b new
# 6   b   b

All “a” in our data frame were replaced by the character string “new”.

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.
You need to agree with the terms to proceed

Menu
Top