Count the number of pattern matches in R dataframe column

To count the number of pattern matches in R we use str_count() function. Let’s see how to get the count of pattern matches in R with an example.

Let’s first create the dataframe.

df1 = data.frame(Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa'), 
                 Mathematics_score=c(45,78,44,89,66,NaN,NaN))
df1

so the dataframe will be

Count the number of pattern matches in R dataframe column 1

 

Count the number of pattern matches in R:

str_count() function is used to count the number of pattern matches in R

library(stringr)
df1$A_count <- str_count(df1$Name,"a")
df1

number of “a” in the column “Name” is counted as shown. So the resultant dataframe will be,

Count the number of pattern matches in R dataframe column 2

                                                                                             

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts