R语言 替换向量的元素 – replace() 函数
R语言中的 replace() 函数用来替换指定的字符串向量x中的值,这些值在列表中给出了索引。
语法: replace(x, list, values)
参数:
x: 矢量
list: 指数
values: 替换值
例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"