Ram
Ram

Reputation: 331

Selecting elements from list

I have a list of names in a list, such as:

site<-list("site2-site22" ,"site2-site45", "site4-site2", "site6-site2",
           "site9-site27", "site20-site150", "site25-site272", "site32-site47",
           "site62-site74", "site272-site280")

From the list, I need to select those elements which has site2 in it, either before or after -

When I use grep command as below:

grep("site2",site,value=T)

It gives me all values starting from site2, that is my results looks like:

"site2-site22"    "site2-site45"    "site4-site27"    "site9-site27" 
"site20-site150"  "site25-site272"  "site272-site280"

How can i only select site2 from the list?

Upvotes: 2

Views: 185

Answers (2)

Suraj
Suraj

Reputation: 36577

grep("site2-|-site2$",site,value=T)

Upvotes: 1

joran
joran

Reputation: 173627

I'm sure there are tons of other ways to do this with regular expressions, but this simple one works:

grep("^site2-|-site2$",site,value=T)

Upvotes: 4

Related Questions