Home > Enterprise >  Change characters using a loop and gsub in R
Change characters using a loop and gsub in R

Time:09-14

I want to create a function in R to replace a series of characters as per input from user.

I have the following script:

string <- "colourise materialise donour"
original <- c("ou", "s")
for (value in original) {
  replacements <- c("o", "z")
    for (change in replacements) {
      string <- gsub(value, change, string)
    }
}
string
> [1] "colorioe materialioe donor"

This script is giving me an unwanted result, because it's probably iterating through both lists. How can I change my script in order to have a result such as this one:

[1] "colorise materialise donor"

I know there's a package to replace using two lists of characters, but would like to use base R for this function.

CodePudding user response:

You don't need two for loops:

string <- "colourise materialise donour"
original <- c("ou", "s")
replacements <- c("o", "z")

for (i in seq_along(original)) {
  string <- gsub(original[i], replacements[i], string)
}

#> string
#[1] "colorize materialize donor"
  • Related