将 gsub 用于 R 中字符串中的特定事件?

ice*_*fee 6 r gsub

我有两个字符串:

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.")
Run Code Online (Sandbox Code Playgroud)

我想将两个字符串中第三次出现的单词 cat 更改为 dog。

理想的情况下,string1string2内容如下:

mystring1
[1] "hello i am a cat.  just kidding, i'm not a cat i'm a dog.  dogs are the best animal.  not cats!"

mystring2
[1] "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."
Run Code Online (Sandbox Code Playgroud)

这样做的最佳方法是什么?到目前为止,我只用于gsub替换字符,但我不知道这是否可以用于替换特定出现的字符。

Mar*_*Gal 6

你可以用

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)

Run Code Online (Sandbox Code Playgroud)

这使

> 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."
Run Code Online (Sandbox Code Playgroud)