【发布时间】:2021-01-04 23:32:42
【问题描述】:
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"
您将如何在基础 R 中实现上述目标?
提供的最佳选项是 for 循环。只是想知道在此期间是否有人想到了更好的选择。
【问题讨论】: