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.