带有 c(pattern1 = replacement1) 选项的 stringr::str_replace_all 的基本 R 替代方案

base R alternative for stringr::str_replace_all with c(pattern1 = replacement1) option

This question 可能在 stringr::str_replace_all 有这个选项(或众所周知)之前就在寻找类似的答案。我正在使用 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"

您将如何在 base R 中实现上述目标?

提供的最佳选择是 for 循环。只是想知道在此期间是否有人想到了更好的选择。

我们可以使用 for 循环和 base R 中的 gsub,因为参数未向量化,即 ?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.

因此,具有递归赋值的for循环可能是更好的选择

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

tr
#[1] "whatevs_R"            "something_C"          "whatevs_1something_C"