我有数据、一个字符向量(最终我会折叠它,所以我不在乎它是保持向量还是被视为单个字符串)、一个模式向量和一个替换向量。我希望数据中的每个模式都被其各自的替换所替换。我用一个stringr
和一个 for 循环完成了它,但是有没有更像 R 的方法呢?
require(stringr)
start_string <- sample(letters[1:10], 10)
my_pattern <- c("a", "b", "c", "z")
my_replacement <- c("[this was an a]", "[this was a b]", "[this was a c]", "[no z!]")
str_replace(start_string, pattern = my_pattern, replacement = my_replacement)
# bad lengths, doesn't work
str_replace(paste0(start_string, collapse = ""),
pattern = my_pattern, replacement = my_replacement)
# vector output, not what I want in this case
my_result <- start_string
for (i in 1:length(my_pattern)) {
my_result <- str_replace(my_result,
pattern = my_pattern[i], replacement = my_replacement[i])
}
> my_result
[1] "[this was a c]" "[this was an a]" "e" "g" "h" "[this was a b]"
[7] "d" "j" "f" "i"
# This is what I want, but is there a better way?
就我而言,我知道每种模式最多会出现一次,但并非每种模式都会出现。我知道str_replace_all
如果模式可能不止一次出现,我可以使用;我希望解决方案也能提供该选项。我还想要一个使用my_pattern
and的解决方案,my_replacement
以便它可以成为以这些向量作为参数的函数的一部分。