Home » How to Use the replace() Function in R

How to Use the replace() Function in R

by Erma Khan

The replace() function in R can be used to replace specific elements in a vector with new values.

This function uses the following syntax:

replace(x, list, values)

where:

  • x: Name of vector
  • list: Elements to replace
  • values: Replacement values

The following examples show how to use this function in practice.

Example 1: Replace One Value in Vector

The following code shows how to replace the element in position 2 of a vector with a new value of 50:

#define vector of values
data #define new vector with a different value in position 2
data_new #view new vector
data_new

[1]  3 50  8 12 14 15 16 19 22

Notice that the element in position 2 has changed, but every other value in the original vector remained the same.

Example 2: Replace Multiple Values in Vector

The following code shows how to replace the values of multiple elements in a vector with new values:

#define vector of values
data #define new vector with different values in position 1, 2, and 8
data_new #view new vector
data_new

[1]  50 100   6   8  10  12  14 200

Notice that the elements in position 1, 2, and 8 all changed.

Example 3: Replace Values in Data Frame

The following code shows how to replace the values in a certain column of a data frame that meet a specific condition:

#define data frame
df frame(x=c(1, 2, 4, 4, 5, 7),
                 y=c(6, 6, 8, 8, 10, 11))

#view data frame
df

  x  y
1 1  6
2 2  6
3 4  8
4 4  8
5 5 10
6 7 11

#replace values in column 'x' greater than 4 with a new value of 50
df$x  4, 50)

#view updated data frame
df

   x  y
1  1  6
2  2  6
3  4  8
4  4  8
5 50 10
6 50 11

Each value in column ‘x’ that was greater than 4 was replaced with a value of 50.

All other values in the data frame remained the same.

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use tabulate() Function in R
How to Use split() Function in R
How to Use match() Function in R
How to Use replicate() Function in R

Related Posts