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).
Is there a wildcard character, like * in Excel, which lists all elements of vectors which you search for J*?
How do I extract elements that start with either letter 'M' or 'A'. The expected output would be Mar,May,Apr,Aug?
Try:
grep("^J", Months,value=TRUE)
#[1] "Jan" "Jun" "Jul"
grep("^A|^M", Months,value=TRUE)
#[1] "Mar" "Apr" "May" "Aug"
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"
If you happen to have stringr
loaded you could do:
library(stringr)
str_subset(Months, "^J")
[1] "Jan" "Jun" "Jul"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With