當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。