Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subset a vector, based on the condition "contains" a character?

If I have a vector:

Months = month.abb[1:12]

I want to extract all the months that start with Letter J (in this case, Jan, Jun, and Jul).

  1. Is there a wildcard character, like * in Excel, which lists all elements of vectors which you search for J*?

  2. How do I extract elements that start with either letter 'M' or 'A'. The expected output would be Mar,May,Apr,Aug?

like image 884
Sudheer Rao Avatar asked Jun 27 '14 08:06

Sudheer Rao


3 Answers

Try:

 grep("^J", Months,value=TRUE)
 #[1] "Jan" "Jun" "Jul"

grep("^A|^M", Months,value=TRUE)
#[1] "Mar" "Apr" "May" "Aug"
like image 199
akrun Avatar answered Nov 20 '22 17:11

akrun


You'll find the glob2rx function helpful for converting wildcard constructions to regular expressions:

> glob2rx("J*")
[1] "^J"
> grep(glob2rx("J*"), Months, value=TRUE)
[1] "Jan" "Jun" "Jul"
like image 21
Thomas Avatar answered Nov 20 '22 15:11

Thomas


If you happen to have stringr loaded you could do:

library(stringr)

str_subset(Months, "^J")
[1] "Jan" "Jun" "Jul"
like image 1
dmi3kno Avatar answered Nov 20 '22 16:11

dmi3kno