The replace() function in R: How to use replace function in R?

replace() function in R

In this article, we will show you how to use the replace() function in R. The replace() function helps you replace the specified values in the R object with new values. Let’s follow this article to learn more about it with the explanation and examples below.

Replace() function in R

What does replace() do in R?

The replace() function in R can help you replace the specified values in the vector, the array, the matrix, or the data frame with new values. 

Syntax:

replace(data, list, values)

Parameters:

  • data: The name of the R object.
  • list: The list of the index of the R object.
  • values: The new values.

After learning the usage and syntax of the replace() function, you will learn how to use it in the next title below.

How to use the replace function in R?

You can use the replace() function to replace a single value or multiple values in the vector, the array, or the data frame.

Replace a single value in the vector

You can replace a single value in the vector by the replace() function.

Look at the example below.

vector <- c(11,22,33,44,55,66,77,88,99)

# Replace the value in the second index with 2
replace(vector,2,2)

Output

[1] 11 2 33 44 55 66 77 88 99

Replace multiple values in the vector

You can replace multiple values in the vector by the replace() function.

Look at the example below.

vector <- c(11,22,33,44,55,66,77,88,99)

# Replace the value in position 2,3,4 with the values 3, 4, and 5
replace(vector,c(2,3,4), c(3,4,5))

Output

[1] 11 3 4 5 55 66 77 88 99

You can replace the elements in an array by the same method as the vector above.

Replace elements in the data frame

You can replace the elements in the data frame by the replace() function.

Look at the example below.

# Create the data frame.
df <- data.frame(
     Student = c('Toi', 'Peter', 'Linda', 'Maguire', 'Valverde', 'Kroos'),
     Score = c(10, 9, 8, 7, 7.5, 8.5)
)
df

Output

  Student  Score
1 Toi      10.0
2 Peter    9.0
3 Linda    8.0
4 Maguire  7.0
5 Valverde 7.5
6 Kroos    8.5

Let’s see how it changes when using the replace() function.

# Replace the element that the score is greater or equal to 9.0 with 8.75
df$Score = replace(df$Score, df$Score >= 9.0, 8.75)
df

Output

  Student  Score
1 Toi      8.75
2 Peter    8.75
3 Linda    8.00
4 Maguire  7.00
5 Valverde 7.50
6 Kroos    8.50

Summary

You have learned the replace() function in R. By this function, you can change the value of the elements in the vector, the array, or the data frame. If you have any questions about this guide, feel free to leave your comment below. I will answer your questions. Thanks!

Maybe you are interested:

Posted in R

Leave a Reply

Your email address will not be published. Required fields are marked *