请参考此帖子和答案 - 感谢@TheodoreLytras:
text <- c("While all my efforts to pacify him failed, I still hoped that he would continue to value our friendship. We had been great friends for the past 18 years, and I don't know why a simple difference of opinion should make him so mad! Well, life is strange, and has its ways, I guess")
mgsub <- function(pattern, replacement, x, ...) {
if (length(pattern)!=length(replacement)) {
stop("pattern and replacement do not have the same length.")
}
result <- x
for (i in 1:length(pattern)) {
result <- gsub(pattern[i], replacement[i], result, ...)
}
result
}
patterns <- c("While all my efforts",
"to pacify him",
"failed",
"I still hoped",
"we had been great friends",
"so mad")
replacements <- c("<my-attempt>",
"<to-make-things-better>",
"<failure>",
"<hope>",
"<we-were-friends>",
"<unhappy>")
mgsub(pattern = patterns, replacement = replacements, x = text)