Using gsub for a specific occurrence in a string in R?

You could use

mystring1 <- c("hello i am a cat.  just kidding, i'm not a cat i'm a cat.  dogs are the best animal.  not cats!")
mystring2 <- c("hello i am a cat.  just kidding, i'm not a cat i'm a cat.  but i have a cat friend that is a cat who knows a cat knowing a cat.")

sub("((cat.*?){2})\\bcat\\b", "\\1dog", mystring1, perl=TRUE)

which gives

> sub("((cat.*?){2})\\bcat\\b", "\\1dog", c(mystring1, mystring2), perl=TRUE)
[1] "hello i am a cat.  just kidding, i'm not a cat i'm a dog.  dogs are the best animal.  not cats!"                                
[2] "hello i am a cat.  just kidding, i'm not a cat i'm a dog.  but i have a cat friend that is a cat who knows a cat knowing a cat."

Tags:

R

Gsub