How to Exchange Particular Values in Vector in R (2 Examples)

In this R tutorial you’ll learn how to change certain values in vectors or arrays.

Creation of Example Data

x <- c("a", "b", "a", "f", "e", "a")      # Example vector in R
x                                         # Return values to RStudio console
# "a" "b" "a" "f" "e" "a"

Example 1: Apply replace() Function to Exchange Values in Vector

x_updated1 <- replace(x,                  # Using replace() function
                      x == "a",
                      "XXX")
x_updated1                                # Print new vector
# "XXX" "b"   "XXX" "f"   "e"   "XXX"

Example 2: Use [] to Exchange Values in Vector

x_updated2 <- x                           # Replicating vector object
x_updated2[x_updated2 == "a"] <- "XXX"    # Using square brackets
x_updated2                                # Return updated vector
# "XXX" "b"   "XXX" "f"   "e"   "XXX"

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