简体   繁体   English

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

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

I have two strings:我有两个字符串:

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

I want to change the third occurrence of the word cat in both strings to dog.我想将两个字符串中单词 cat 的第三次出现更改为 dog。

Ideally, string1 and string2 would read:理想情况下, 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."

What is the best way of doing this?这样做的最佳方法是什么? Up until now I have only used gsub to replace characters but I don't know if this can be used to replace specific occurrences of a character.到目前为止,我只使用gsub替换字符,但我不知道这是否可以用来替换特定出现的字符。

You could use你可以使用

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)

which gives这使

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

You can use gsubfn您可以使用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."

Or, if it needs to be surrounded by word boundaries,或者,如果它需要被单词边界包围,

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