I have a dataframe in R. I would like to count the number of cells in a column that contain a specific string.
Using the example data below, I want to count how many cells in the column a contain the string "purple." (2)
I imagine something like this: sum(df$a %contains% "purple")
a <- c("red, white", "white", "blue, purple", "purple")
b <- c("white", "white, yellow", "purple", "purple, blue, yellow")
df <- data.table(a, b)
CodePudding user response:
You could do with str_count
sum(stringr::str_count(df$a, pattern = "purple"))
CodePudding user response:
Use grepl
(only works if there are no more than one occurrence per string):
sum(grepl("purple", a))
# [1] 2