[R] vectorized sub, gsub, grep, etc.
John Thaden
jjthaden at flash.net
Mon Aug 3 06:42:16 CEST 2015
Adam,
The original posting gave a function sub2 whose aim differs both from your functions' aim and from the intent of mgsub() in the qdap package:
> Here is code to apply a different
> pattern and replacement for every target. #Example
X <- c("ab", "cd", "ef")
patt <- c("b", "cd", "a")
repl <- c("B", "CD", "A")
The first pattern ('b') and the first replacement ('B') therefore apply only to the first target ('ab'), the second to the second, etc. The function achieves its aim, giving the correct answer 'aB', 'CD', 'ef'.
mgsub() satisfies a different need, testing all targets for matches with any pattern in the vector of patterns and, if a match is found, replacing the matched target with the replacement value corresponding to the matched pattern. It, too, achieves its aim, giving a different (but also correct) answer 'AB', 'CD', 'ef'.
Regards,-John
#Example
X <- c("ab", "cd", "ef")
patt <- c("b", "cd", "a")
repl <- c("B", "CD", "A")
[[alternative HTML version deleted]]
More information about the R-help
mailing list