When grep() should be used?
grep is preferred to opt select columns based on the name of the column.
Example: In this example, we have selected entire columns having the character ‘S’ in the header name.
R
library (dplyr) # creating a data frame df <- data.frame (Department = c ( 'CSE' , 'IT' , 'ECE' , 'EE' , 'ME' ), Strength = c (80, 76, 75, 65, 70), Score = c (75, 70, 65, 60, 60)) # select columns that contain the string # 'S' in their name df %>% select ( grep ( 'S' , colnames (df))) |
Output:
Count the Number of Rows that Contain a Certain String. grep() function should be used to count the number of rows in the given data frame that matches with a certain string.
Example: In this example, we have counted the number of rows, in which the header has ‘S’ in it.
R
library (dplyr) # creating a data frame df <- data.frame (Department = c ( 'CSE' , 'IT' , 'ECE' , 'EE' , 'ME' ), Strength = c (80, 76, 75, 65, 70), Score = c (75, 70, 65, 60, 60)) # select and count columns that contain # the string 'S' in their name df %>% length ( grep ( 'S' , colnames (df))) |
Output:
Difference Between grep() vs. grepl() in R
In this article, we will discuss the difference between grep() and grepl() in R programming language.