Grep command
I use my own functions multiGrep and multiGrepl:
multiGrep = function(patterns, x, ..., sort = TRUE, invert = FALSE)
{
if (invert)
{
out = multiIntersect(lapply(patterns, grep, x, ..., invert = TRUE))
} else
out = unique(unlist(lapply(patterns, grep, x, ..., invert = FALSE)));
if (sort) out = sort(out);
out;
}
multiGrepl = function(patterns, x, ...)
{
mat = do.call(cbind, lapply(patterns, function(p)
as.numeric(grepl(p, x, ...))));
rowSums(mat)>0;
}
multiGrep(some, all)
[1] 1 3 6
multiGrepl(some, all)
[1] TRUE FALSE TRUE FALSE FALSE TRUE multiGrep(some, all, invert = TRUE) [1] 2 4 5 Peter
On Thu, May 19, 2016 at 4:09 PM, Steven Yen <syen04 at gmail.com> wrote:
What is a good way to grep multiple strings (say in a vector)? In the
following, I grep ants, cats, and fox separately and concatenate them,
is there a way to grep the trio in one action? Thanks.
all<-c("ants","birds","cats","dogs","elks","fox"); all
[1] "ants" "birds" "cats" "dogs" "elks" "fox"
some<-c("ants","cats","fox"); some
[1] "ants" "cats" "fox"
j<-c(
grep(some[1],all,value=F),
grep(some[2],all,value=F),
grep(some[3],all,value=F)); j; all[j]
[1] 1 3 6
[1] "ants" "cats" "fox"
[[alternative HTML version deleted]]
______________________________________________ R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.