计算R中的单词出现次数

LNA*_*LNA 21 string r

是否有用于计算特定关键字包含在数据集中的次数的函数?

例如,如果dataset <- c("corn", "cornmeal", "corn on the cob", "meal")计数为3.

42-*_*42- 35

我们暂时假设您想要包含"玉米"的元素数量:

length(grep("corn", dataset))
[1] 3
Run Code Online (Sandbox Code Playgroud)

在更好地了解R的基础之后,您可能需要查看"tm"包.

编辑:我意识到这一次你想要任何"玉米",但在未来你可能想要得到"玉米"这个词.在r-help上,Bill Dunlap指出了一个更紧凑的grep模式来收集整个单词:

grep("\\<corn\\>", dataset)
Run Code Online (Sandbox Code Playgroud)

  • 对.这突出了原始问题的模糊性.我无法弄清楚为什么4是正确的数字.你的方法将返回2为"玉米",1为"饭",1为"玉米面".计算以空格分隔的单词"corn"的贪婪方式可能是:length(grep("^ corn $ | ^ corn | corn $",数据集)) (3认同)

pet*_*ner 29

另一种非常方便直观的方法是使用包的str_count功能stringr:

library(stringr)
dataset <- c("corn", "cornmeal", "corn on the cob", "meal")

# for mere occurences of the pattern:
str_count(dataset, "corn")
# [1] 1 1 1 0

# for occurences of the word alone:
str_count(dataset, "\\bcorn\\b")
# [1] 1 0 1 0

# summing it up
sum(str_count(dataset, "corn"))
# [1] 3
Run Code Online (Sandbox Code Playgroud)