R Exchange Particular Character String by NA (2 Examples)

In this tutorial, I’ll illustrate how to replace certain character strings with NA in R.

Example 1: Vector – Exchanging Particular Character Value by NA

my_x <- c("foo", "bar", "XXX", "foo", "bar")                   # Example vector in R
my_x                                                           # Showing example vector in RStudio
# [1] "foo" "bar" "XXX" "foo" "bar"
my_x[my_x == "foo"] <- NA                                      # Exchange character value
my_x                                                           # Showing new vector in RStudio
# [1] NA    "bar" "XXX" NA    "bar"

Example 2: Data Frame – Exchanging Particular Character Value by NA

my_df <- data.frame(x = c("foo", "bar", "XXX", "foo", "bar"),  # Example data frame in R
                    y = c("XXX", "bar", "foo", "bar", "foo"))
my_df                                                          # Showing example data frame in RStudio
#     x   y
# 1 foo XXX
# 2 bar bar
# 3 XXX foo
# 4 foo bar
# 5 bar foo
my_df[my_df == "foo"] <- NA                                    # Exchange character value in all columns
my_df                                                          # Showing new data frame in RStudio
#      x    y
# 1 <NA>  XXX
# 2  bar  bar
# 3  XXX <NA>
# 4 <NA>  bar
# 5  bar <NA>

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