📜  在 R 编程中替换向量的元素 – replace()函数

📅  最后修改于: 2022-05-13 01:55:10.931000             🧑  作者: Mango

在 R 编程中替换向量的元素 – replace()函数

R 语言中的replace()函数用于将指定字符串向量 x 中的值替换为列表中给定的索引值。

示例 1:

# 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

输出 :

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

示例 2:

# 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

输出:

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