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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

[1] "GFG"   "gfg"   "Geeks"
[1] "GFG"   "GeeksforGeeks" "Geeks"  

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# replace function
  
# Initializing a string vector
x <- c("GFG", "gfg", "Geeks")
  
# Getting the strings
x
  
# Calling replace() function to replace
# the word GFG at index 1 and Geeks 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

chevron_right


Output:

[1] "GFG"   "gfg"   "Geeks"
[1] "A"   "gfg" "B"  
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.