R String Search
Pattern searching tests each string in a vector against a pattern. grep and grepl answer that test in different forms.
Positions of matches
grep looks for ap inside each word. The output gives the positions of the two matching words.
words <- c("apple", "apricot", "banana", "plum")
print(grep("ap", words))Words instead of positions
The value argument asks for the matching words themselves. The output holds the words rather than their positions.
words <- c("apple", "apricot", "banana", "plum")
print(grep("ap", words, value = TRUE))A logical answer for each word
grepl tests each word for an. The output holds one TRUE or FALSE value for each word.
words <- c("apple", "apricot", "banana", "plum")
print(grepl("an", words))Anchors at the start and end
The ^ mark ties ap to the start of a word. The $ mark ties e to the end of a word.
words <- c("apple", "apricot", "banana", "plum")
print(grep("^ap", words))
print(grep("e$", words, value = TRUE))A set of characters and no match
The bracket pattern matches any one vowel. The second search looks for z and finds nothing.
words <- c("apple", "apricot", "banana", "plum")
print(grep("[aeiou]", c("sky", "apple", "plum")))
print(grep("z", words))Example
fruits <- c("pear", "peach", "plum", "melon")
print(grep("^pe", fruits, value = TRUE))
print(grepl("l", fruits))Key points
- A pattern is a piece of text to look for inside each string.
- grep gives back the positions of the strings that match.
- The value = TRUE form of grep gives back the matching strings.
- grepl gives back TRUE or FALSE for each string in the vector.
- The ^ mark anchors a pattern to the start of a string.
- The $ mark anchors a pattern to the end of a string.
- A pattern in square brackets matches any one character from the set.
In this example the anchor ^pe picks out the words that start with pe. grepl then reports which words hold the letter l.
Note
A grep with no match gives back integer(0).
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does grep give back when no string in the vector matches the pattern?