The str_replace (and preg_replace ) function in PHP replaces all occurrences of the search string with the replacement string. What interests me the most is that if search and replace args are arrays (we call these vectors in R), then str_replace takes a value from each array (vector) and uses them to search and replace with the item.
In other words, does R (or some package R) have a function to perform the following actions:
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)
So, I'm looking for something like chartr , but for search patterns and replacement strings of arbitrary number of characters. This cannot be done with a single call to gsub() since its replacement argument can only be one line, see ?gsub . So my current implementation is similar:
xxx_replace_xxx <- function(string, patterns, replacements) { for (i in seq_along(patterns)) string <- gsub(patterns[i], replacements[i], string, fixed=TRUE) string }
However, I am looking for something much faster if length(patterns) large - I have a lot of data to process and I am not satisfied with the current results.
Examples of these benchmarking toys:
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))