簡體   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