3

I am not sure if this question has been addressed before, at least in direct form.

I have a paragraph like this:

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

I want the following replacements in the passage:

 "While all my efforts" -> <my-attempt>
 "to pacify him" -> <to-make-things-better>
 "failed" -> <failure>
 "I still hoped" -> <hope>
 "we had been great friends" -> <we-were-friends>
 "so mad" -> <unhappy>

Rest of the text can remain as is.

Is it possible to do this with a single call to a regular expression function in R ?

Thanks!

1 Answers1

3

See this post and answer - credit to @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)
# [1] "<my-attempt> <to-make-things-better> <failure>, <hope> 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 <unhappy>! Well, life is strange, and has its ways, I guess"
Community
  • 1
  • 1
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116