3

I am trying to count how many times a keyword appears in a string. In the following variable text, I would like to count how many times keyword appears in text. The result should display 3 because AWAY appears twice and WIN appears once in the string.

text<- "AWAYTEAM IS XXX. I THINK THEAWAYTEAM WILL WIN"
keyword<- c("AWAY","WIN")

Any ideas?

user9532692
  • 584
  • 7
  • 28
  • Does this answer your question? [grep using a character vector with multiple patterns](https://stackoverflow.com/questions/7597559/grep-using-a-character-vector-with-multiple-patterns) – user438383 Aug 22 '21 at 16:14

2 Answers2

2

We may use str_count with sum

library(stringr)
sum(str_count(text, keyword))
[1] 3
akrun
  • 874,273
  • 37
  • 540
  • 662
1

One possibility using stringr

library(stringr)

text<- "AWAYTEAM IS XXX. I THINK THEAWAYTEAM WILL WIN"
keyword<- c("AWAY","WIN")

length(unlist(str_extract_all(text, keyword)))
#> [1] 3

Created on 2021-08-22 by the reprex package (v2.0.0)

Peter
  • 11,500
  • 5
  • 21
  • 31