The grepl() function in R is used for pattern matching and searching within strings. It’s a variation of the grep() function, where grepl() returns a logical vector suggesting whether a pattern is found in each element of a character vector.
Syntax
grepl(pattern, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)
Parameters
Name | Description |
pattern | It is a regular expression or string for fixed=TRUE. |
x | It is a string, the character vector. |
perl | Logical. Should Perl-compatible regexps be used? Has priority been overextended? |
fixed | It is logical. If the TRUE, the pattern is a string to be matched. Overrides all conflicting arguments. |
useBytes | It is logical. If TRUE, the matching is done byte-by-byte rather than character-by-character. |
Return value
It returns TRUE if a string contains the pattern; otherwise, it is FALSE.
Example 1: Searching for simple patterns in character vectors
In this figure, we are searching for character “K” in the vector rv, and if it matches, it returns TRUE; otherwise, it is FALSE.
rv <- c("KHUSHI", "KRUNAL", "MATE", "AUS")
grepl("K", rv)
Output
[1] TRUE TRUE FALSE FALSE
Example 2: Using regular expressions
In the figure, we check if the string sv contains any numeric digits. If there is a numeric digit, it returns TRUE; otherwise, it is FALSE.
sv <- "Infosys is currently trading at 1435 Rs."
op <- grepl("\\d+", sv)
print(op)
Output
[1] TRUE
Example 3: Passing ignore.case argument
Pass the ignore.case = TRUE to ignore the letters’ cases while searching for patterns. It will ignore whether the letters are in capital or small letters in the string.
In the below figure, we passed ignore.case = TRUE to the grepl() function, which means that no matter if the input character is small or capital, if it matches, it returns TRUE; otherwise, it returns FALSE.
rv <- c("khushi", "KRUNAL", "MATE", "AUS")
grepl("K", rv, ignore.case = T)
Output
[1] TRUE TRUE FALSE FALSE
If we pass ignore.case = F or FALSE, it will only return the TRUE on the second position. It will check strictly.
rv <- c("khushi", "KRUNAL", "MATE", "AUS")
grepl("K", rv, ignore.case = F)
Output
[1] FALSE TRUE FALSE FALSE
You will find all the information about the grepl() method in the below image in RStudio.
The functions like grep(), grepl(), regexpr(), gregexpr(), and regexec() search for matches to argument patterns within every item of a character vector.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.