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 RFunction.com 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 <- "http://rfunction.com/code/1202/BarackObamaTweets.txt" > 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  "Last night, Senate Democrats tried to pass a piece of the President's jobs plan to prevent layoffs of teachers, cops, and firefighters." > tweets  "Of the people who gave this quarter, 257,635 people were entirely new to this movement." > tweets  "We've been asking a lot of you, and you've delivered. Thank you. Here's a quick reminder of what we're fighting for: http://t.co/lHiCWvF" > > these  42 175 212 247 271 272 321 322 481 679 > > tweets[these]  "When he wanted to be VP, Mitt Romney gave John McCain 23 years of tax returns. Now Americans only get to see one: http://t.co/yVAwXlfp"  "How many jobs did Mitt Romney create as a corporate buyout specialist? Even he can't get his story straight: http://t.co/k6fgjuLw"  "Romney said during last night's debate that he wants to give relief to the middle class. But his tax plan wouldn't: http://t.co/7caE69AM"  "Mitt Romney claims he created more jobs as Mass. governor than President Obama has created. Here's the reality: http://t.co/BQE7YCgp"  "Mitt Romney's son thinks President Obama should release his birth certificate. Guess he doesn't have one of our mugs? http://t.co/45SryWn4"  "Why won\031t Mitt Romney release his tax returns? http://t.co/iJZWv7DB"  "Where does Mitt Romney stand on the payroll tax? Help find out: http://t.co/4fQEknIE"  "Press Secretary @BenLaBolt on the top 10 ways Mitt Romney would stack the deck against the middle class: http://t.co/zt9tXkrA"  "The two sides of Mitt Romney can\031t agree on much\024except wanting to be President. Watch: http://t.co/GyfG0JcN"  "Let foreclosures hit the bottom? Our take: Romney won't lift a finger to protect the middle class. http://t.co/nwNL6Qg8"
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.