Replace the Elements of a Vector in R Programming – replace() Function

replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.

Syntax: replace(x, list, values)

Parameters:
x: vector
list: indices
values: replacement values

Example 1:




# R program to illustrate
# replace function
  
# Initializing a string vector
x <- c("GFG", "gfg", "Beginner")
  
# Getting the strings
x
  
# Calling replace() function to replace
# the word gfg at index 2 with the 
# w3wiki element
y <- replace(x, 2, "w3wiki")
  
# Getting the new replaced strings
y


Output :

[1] "GFG"   "gfg"   "Beginner"
[1] "GFG"   "w3wiki" "Beginner"  

Example 2:




# R program to illustrate
# replace function
  
# Initializing a string vector
x <- c("GFG", "gfg", "Beginner")
  
# Getting the strings
x
  
# Calling replace() function to replace
# the word GFG at index 1 and Beginner at
# index 3 with the A and B elements
# respectively
y <- replace(x, c(1, 3), c("A", "B"))
  
# Getting the new replaced strings
y


Output:

[1] "GFG"   "gfg"   "Beginner"
[1] "A"   "gfg" "B"