Replace Values in Vector in R (2 Examples)


In this R programming tutorial you’ll learn how to exchange given values in a vector.

Table of contents:

Let’s dive into it…


Creation of Example Data

As a first step, we have to define some data that we can use in the following examples:

my_vec <- c(4, 1, 4, 3, 1, 7, 5, 1, 6)    # Create example vector
my_vec                                    # Print example vector
# 4 1 4 3 1 7 5 1 6

The previous output of the RStudio console shows the structure of our example data: It is a vector (or array) containing different numeric values.


Example 1: Replacing Value in Vector Using Square Brackets

Example 1 shows how to change specific values in our vector using square brackets in R. Have a look at the following R code:

my_vec_new1 <- my_vec                     # Duplicate vector
my_vec_new1[my_vec_new1 == 1] <- 999      # Replace values
my_vec_new1                               # Print new vector
# 4 999   4   3 999   7   5 999   6

The previous output of the RStudio console shows our new vector object. As you can see, the value 1 was conditionally replaced by 999.


Example 2: Replacing Value in Vector Using replace() Function

This example illustrates how to apply the replace function to modify certain vector elements in R.

Within the replace function, we have to specify the name of our vector object (i.e. my_vec, a logical condition (i.e. my_vec == 1), and the value we want to insert (i.e. 999):

my_vec_new2 <- replace(my_vec,            # Replace values
                       my_vec == 1,
my_vec_new2                               # Print new vector
# 4 999   4   3 999   7   5 999   6

The output of the previous R syntax is exactly the same as in Example 1. Whether you prefer to use square brackets or the replace function to exchange given values in a vector is a matter of taste.


Video, Further Resources & Summary

I have recently published a video on the Statistics Globe YouTube channel, which illustrates the content of this tutorial. Please find the video below.



In addition, you may want to read the related R tutorials of my homepage.


In this tutorial you learned how to change certain values in vectors or arrays in R. In case you have any additional questions, please tell me about it in the comments.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

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.