Counting whole word/number occurrences with str_count in R

浪子不回头ぞ 提交于 2019-12-02 01:26:19

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

Try putting word boundaries around your keywords:

keywords <- c("honda","civic","toyota","auris","nissan","skyline","1988","1400","159")
keywords <- paste0("\\b", keywords, "\\b")

In regex lingo, \bhonda\b says to match the isolated word honda. Hence hondas would not match because it has an extra letter at the end.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!