PHP中的str_replace(和preg_replace)函数用替换字符串替换所有出现的搜索字符串。我在这里最感兴趣的是,如果search
和replace
args是数组(在R中,我们称其为向量),str_replace
则从每个数组(向量)中获取一个值,并使用它们搜索和替换主题。
换句话说,R(或某些R包)是否具有执行以下功能:
string <- "The quick brown fox jumped over the lazy dog."
patterns <- c("quick", "brown", "fox")
replacements <- c("slow", "black", "bear")
xxx_replace_xxx(string, patterns, replacements) ## ???
## [1] "The slow black bear jumped over the lazy dog."
所以我正在寻找类似的东西chartr
,但要寻找搜索模式和任意数量字符的替换字符串。无法通过一次调用来完成此操作,gsub()
因为其replacement
参数只能是单个字符串,请参见?gsub
。所以我当前的实现是这样的:
xxx_replace_xxx <- function(string, patterns, replacements) {
for (i in seq_along(patterns))
string <- gsub(patterns[i], replacements[i], string, fixed=TRUE)
string
}
但是,如果length(patterns)
大小很大,我正在寻找更快的东西-我要处理大量数据,并且对当前结果不满意。
用于基准测试的示例性玩具数据:
string <- readLines("http://www.gutenberg.org/files/31536/31536-0.txt", encoding="UTF-8")
patterns <- c("jak", "to", "do", "z", "na", "i", "w", "za", "tu", "gdy",
"po", "jest", "Tadeusz", "lub", "razem", "nas", "przy", "oczy", "czy",
"sam", "u", "tylko", "bez", "ich", "Telimena", "Wojski", "jeszcze")
replacements <- paste0(patterns, rev(patterns))
在您的示例中,使用PCRE而不是固定匹配需要大约1/3的时间。
xxx_replace_xxx_pcre <- function(string, patterns, replacements) {
for (i in seq_along(patterns))
string <- gsub(patterns[i], replacements[i], string, perl=TRUE)
string
}
system.time(x <- xxx_replace_xxx(string, patterns, replacements))
# user system elapsed
# 0.491 0.000 0.491
system.time(p <- xxx_replace_xxx_pcre(string, patterns, replacements))
# user system elapsed
# 0.162 0.000 0.162
identical(x,p)
# [1] TRUE
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句