我有数据,一个字符向量(最终我会折叠它,所以我不在乎它是否保持向量或者它被视为单个字符串),一个模式向量和一个替换向量。我希望数据中的每个模式都被其各自的替换替换。我用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
和my_replacement
的解决方案,以便它可以作为以这些向量为参数的函数的一部分。
for循环出了什么问题?它们非常适合这种情况,您可以反复修改矢量。 – hadley 2013-02-16 14:38:56