2

This question was seeking a similar answer probably before stringr::str_replace_all had that option (or was well known). I'm copying the gist of my answer below, using str_replace_all.


tr <- c("whatevs_1", "something_52", "whatevs_1something_52")

tr
#> [1] "whatevs_1"             "something_52"          "whatevs_1something_52"

patterns <- sprintf('_%s$', c('1','14','22','50','52','57','76','1018','2001','3301','6005'))
replacements <- sprintf('_%s' , c('R','I', 'P', 'O', 'C', 'D', 'M', 'L',   'S',   'K',   'G'))
                        
names(replacements) <- patterns

stringr::str_replace_all(tr, replacements)
#> [1] "whatevs_R"            "something_C"          "whatevs_1something_C"

How would you achieve the above in base R?

The best option provided is a for loop. Just wondering if anyone had thought of a better alternative in the meantime.

Fons MA
  • 1,142
  • 1
  • 12
  • 21

1 Answers1

4

We can use a for loop with gsub from base R as the arguments are not vectorized i.e. ?gsub

pattern - If a character vector of length 2 or more is supplied, the first element is used with a warning. Missing values are allowed except for regexpr, gregexpr and regexec.

replacement - If a character vector of length 2 or more is supplied, the first element is used with a warning. If NA, all elements in the result corresponding to matches will be set to NA.

Therefore, a for loop with recursive assignment may be the better option

for(i in seq_along(patterns)) tr <- gsub(patterns[i], replacements[i], tr)

tr
#[1] "whatevs_R"            "something_C"          "whatevs_1something_C"
akrun
  • 874,273
  • 37
  • 540
  • 662