Counting whole word/number occurrences with str_count in R

后端 未结 2 1646
醉酒成梦
醉酒成梦 2021-01-21 23:57

Similar to this case, i would like to count the number of occurrences of multiple words and numbers that occur in a vector of sentences with str_count of the stringr package.

2条回答
  •  花落未央
    2021-01-22 00:14

    Using sprintf you can add word boundaries:

    number_of_keywords_df <- str_count(df, paste(sprintf("\\b%s\\b", keywords), collapse = '|'))
    number_of_keywords_df
    

    Which yields

    [1] 3 2 2
    

提交回复
热议问题