我有數據,一個字符向量(最終我會摺疊它,所以我不在乎它是否保持向量或者它被視爲單個字符串),一個模式向量和一個替換向量。我希望數據中的每個模式都被其各自的替換替換。我用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