【问题标题】:Using gsub for a specific occurrence in a string in R?将 gsub 用于 R 中字符串中的特定事件?
【发布时间】:2020-06-15 13:34:00
【问题描述】:

我有两个字符串:

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 替换字符,但我不知道这是否可以用于替换特定出现的字符。

【问题讨论】:

  • 试试sub("(.*?cat.*cat.*)cat", "\\1dog", mystring1)

标签: r gsub


【解决方案1】:

你可以使用

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."

【讨论】:

  • 最好用\\b's 包围cat
  • 为什么不使用sub("((cat.*?){2})cat", "\\1dog", c(mystring1, mystring2), perl=T)
  • @ChrisRuehlemann 好点,但 OP 没有要求在一个语句中同时处理两个字符串。
【解决方案2】:

您可以使用gsubfn

library(gsubfn)
p <- proto(fun = function(this, x) if(count == 3) 'dog' else x)
gsubfn('cat', p, c(mystring1, mystring2))

# [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."

或者,如果它需要被单词边界包围,

gsubfn('\\bcat\\b', p, 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."

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多