Skip to content
Back to formatted view

Raw Message

Message-ID: <CA998306-C0F0-474D-855A-4764BF10B977@comcast.net>
Date: 2016-05-19T23:57:22Z
From: David Winsemius
Subject: Grep command
In-Reply-To: <b988efd2-cacd-60c3-0fd2-af7ed2b33794@gmail.com>

> On 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"

j <- grep( paste0( some, collapse="|") , all ); j; all[j]
#----------
[1] 1 3 6
[1] "ants" "cats" "fox" 

-- 

David Winsemius
Alameda, CA, USA