0

这个问题类似于 Stack question Regular expression parsed with grepl replacement

目标是解析正则表达式并仅替换匹配的模式。这个例子:

data <- c("cat 6kg","cat g250", "dog","cat 10 kg", "no cat") 

要解析感兴趣的匹配项cat

data[grepl("cat",data)]
[1] "cat 6kg"   "cat g250"  "cat 10 kg" "no cat"

理想的结果会替换所有出现的catwith chicken

[1] "chicken 6kg"   "chicken g250"  "chicken 10 kg" "no chicken"

知道如何实现这一目标吗?多谢你们。

4

1 回答 1

1

使用 gsub:

gsub("cat", "chicken", data)

[1] "chicken 6kg"   "chicken g250"  "dog"           "chicken 10 kg" "no chicken"

或者如果你只想要包含 cat 的:

gsub("cat", "chicken", data[grepl("cat",data)])

[1] "chicken 6kg"   "chicken g250"  "chicken 10 kg" "no chicken" 
于 2015-08-20T14:39:50.737 回答