是否有用于计算特定关键字包含在数据集中的次数的函数?
例如,如果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)
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)