grep(pattern, x)
Search for a particular pattern in each element of a vector x. I remember the ordering of the arguments by remembering that the arguments follow the order of "needle in a haystack", where pattern is the needle and x is the haystack.
  • pattern – A regular expressions pattern, though a simple character string is probably sufficient for many people’s needs.
  • x – A character vector.

Example. A text file of Barack Obama’s tweets is loaded from and put into a character vector. The grep function is used to check which tweets include Romney’s name, and then we print those out. Notice the warning, which in this instance specifies that some unusual characters were included in the tweets.
> URL    <- ""
> tweets <- read.delim(URL)
> tweets <- as.character(tweets[,1])
> these <- grep("[Rr]omney", tweets)
Warning messages:
1: In grep("[Rr]omney", tweets) :
  input string 1437 is invalid in this locale
2: In grep("[Rr]omney", tweets) :
  input string 2013 is invalid in this locale
3: In grep("[Rr]omney", tweets) :
  input string 2069 is invalid in this locale
> tweets[647]
[1] "Last night, Senate Democrats tried to pass a piece
of the President's jobs plan to prevent layoffs of teachers,
cops, and firefighters."
> tweets[703]
[1] "Of the people who gave this quarter, 257,635 people
were entirely new to this movement."
> tweets[1279]
[1] "We've been asking a lot of you, and you've delivered.
Thank you. Here's a quick reminder of what we're fighting
> these
 [1]  42 175 212 247 271 272 321 322 481 679
> tweets[these]
 [1] "When he wanted to be VP, Mitt Romney gave John McCain
23 years of tax returns. Now Americans only get to see
 [2] "How many jobs did Mitt Romney create as a
corporate buyout specialist? Even he can't get his story
 [3] "Romney said during last night's debate that he
wants to give relief to the middle class. But his tax plan
 [4] "Mitt Romney claims he created more jobs as Mass.
governor than President Obama has created. Here's the
 [5] "Mitt Romney's son thinks President Obama should
release his birth certificate. Guess he doesn't have one of
our mugs?"
 [6] "Why won\031t Mitt Romney release his tax
 [7] "Where does Mitt Romney stand on the payroll tax?
Help find out:"                                                      
 [8] "Press Secretary @BenLaBolt on the top 10 ways
Mitt Romney would stack the deck against the middle
 [9] "The two sides of Mitt Romney can\031t agree on
much\024except wanting to be President.
[10] "Let foreclosures hit the bottom? Our take:
Romney won't lift a finger to protect the middle
Tip. A helpful regular expressions guide may be found here. If you have an alternative recommendation, please send an email or post a link below, especially for ground-up tutorials.

Leave a Reply