繁体   English   中英

使用 gsub 在 R 中的字符串中的特定出现?

[英]Using gsub for a specific occurrence in a string in R?

我有两个字符串:

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

您可以使用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."

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM