当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 replace()用法及代码示例


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

用法: replace(x, list, values)

参数:
x:向量
list: index
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"  



相关用法


注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 Replace the Elements of a Vector in R Programming – replace() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。