gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:06:59 25 4
gpt4 key购买 nike

我有两个字符串:

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。

理想情况下, 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."

这样做的最佳方法是什么?到现在为止我只用过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com