Multiple Text String Modifications in R

Viewed 26

I have multiple strings stored in an atomic vector:

v <- c("The kat ran up the tree", "The dogg ran up the tree", "The squirrrel run up the tree")

I would like to correct the spelling errors:

v <- gsub('kat', 'cat', v)
v <- gsub('dogg', 'dog', v)
v <- gsub('squirrel', 'squirrrel', v)

However I don't like the repetitive code. Is there some way to do the equivalent of this:

v1 <- c('kat', 'dogg', 'squirrrel')
v2 <- c('cat', 'dog', 'squirrel')

v <- gsub(v1, v2, v)
1 Answers

Easiest option is str_replace_all and pass a named vector or list

library(stringr)
str_replace_all(v, setNames(v2, v1))

-output

#[1] "The cat ran up the tree"     
#[2] "The dog ran up the tree"  
#[3]    "The squirrel run up the tree"
Related