我有两个字符串:
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.")
我想将两个字符串中第三次出现的单词 cat 更改为 dog。
理想情况下,
string1
和 string2
会读: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."
这样做的最佳方法是什么?到现在为止我只用过
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 who knows a cat knowing a cat.")
sub("((cat.*?){2})\\bcat\\b", "\\1dog", mystring1, perl=TRUE)
这使
> 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."
关于r - 将 gsub 用于 R 中字符串中的特定事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62389341/