gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:29:27 24 4
gpt4 key购买 nike

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 循环。只是想知道是否有人同时想到了更好的选择。

最佳答案

我们可以使用来自 base Rfor 循环和 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"

关于r - stringr::str_replace_all 的基本 R 替代方案,带有 c(pattern1 = replacement1) 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65571266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com