How to use grep() In R Language

grep() function returns the index at which the pattern is found in the vector. If there are multiple occurrences of the pattern, it returns a list of indices of the occurrences. This is very useful as it not only tells us about the occurrence of the pattern but also of its location in the vector.
 

Syntax: grep(pattern, string, ignore.case=FALSE)

Parameters: 

  • pattern: A regular expressions pattern.
  • string: The character vector to be searched.
  • ignore.case: Whether to ignore case in the search. Here ignore.case is an optional parameter as is set to FALSE by default.

Example 1: To find all instances of specific words in the string.

R




str <- c("Hello", "hello", "hi", "hey")
grep('hey', str)


Output:

4

Example 2: To find all instances of specific words in the string irrespective of case

R




str <- c("Hello", "hello", "hi", "hey")
grep('he', str, ignore.case ="True")


Output:

[1] 1 2 4



Working with Text in R

R Programming Language is used for statistical computing and is used by many data miners and statisticians for developing statistical software and data analysis. It includes machine learning algorithms, linear regression, time series, and statistical inference to name a few. R and its libraries implement a wide variety of statistical and graphical techniques, including linear and non-linear modeling, classical, statistical tests, time-series analysis, classification, clustering, and others. 

Any value written inside the double quote is treated as a string in R. String is an array of characters and these collections of characters are stored inside a variable. Internally R stores every string within double quotes, even when you create them with a single quote. 

Similar Reads

Text Processing in R

Using Built-in Type in R Using Tidyverse module Using regex and external module Using grep()...

Method 1: Using Built-in Type

In this method, we are using a built-in type for text processing in R....

Method 2: Using Tidyverse module

...

Method 3: Using regex and external module

...

Method 4: Using grep()

...