我在一个原子向量中存储了多个字符串:
v <- c("The kat ran up the tree", "The dogg ran up the tree", "The squirrrel run up the tree")
我想纠正拼写错误:
v <- gsub('kat', 'cat', v)
v <- gsub('dogg', 'dog', v)
v <- gsub('squirrel', 'squirrrel', v)
但是我不喜欢重复的代码。有没有类似的方法:
v1 <- c('kat', 'dogg', 'squirrrel')
v2 <- c('cat', 'dog', 'squirrel')
v <- gsub(v1, v2, v)
最简单的选择是str_replace_all
并通过named
vector
或list
library(stringr)
str_replace_all(v, setNames(v2, v1))
与产出
#[1] "The cat ran up the tree"
#[2] "The dog ran up the tree"
#[3] "The squirrel run up the tree"