replace Function in R (Example)

 

This article shows how to exchange values in a vector using the replace function in the R programming language.

The tutorial consists of these contents:

If you want to learn more about these topics, keep reading:

Definition & Basic R Syntax of replace Function

 

Definition: The replace R function exchanges values in a data object.

 

Basic R Syntax: Please find the basic R programming syntax of the replace function below.

replace(x, 1, 2)               # Basic R syntax of replace function

In the following, I’ll explain in an example how to apply the replace function in R programming.

 

Example Data

Have a look at the following example data:

x <- 1:10                      # Create example vector
x                              # Print example vector
# 1  2  3  4  5  6  7  8  9 10

Have a look at the previous output of the RStudio console. It shows that our example data is a numeric vector ranging from 1 to 10.

 

Example: Applying replace() Function in R

This Example explains how to change certain values to different values using the replace function in R.

Within the replace function, we have to specify the name of our data object (i.e. x), the index positions of the values we want to replace (i.e. 3 and 8), and the value that should replace the previous values (i.e. 99):

replace(x, c(3, 8), 99)        # Apply replace function
# 1  2 99  4  5  6  7 99  9 10

The values at index positions 3 and 8 of our original vector were replaced by 99.

 

Video, Further Resources & Summary

Do you need further info on the R codes of this tutorial? Then you might have a look at the following video of my YouTube channel. I explain the R codes of this tutorial in the video:

 

 

In addition, you could read the other articles of this website. A selection of articles is shown here:

 

To summarize: This post showed how to apply the replace function in the R programming language. Let me know in the comments section, in case you have additional questions. Furthermore, please subscribe to my email newsletter to receive updates on the newest articles.

 

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.

Top