有没有一个函数可以计算特定关键字在数据集中出现的次数?
例如,如果为dataset <- c("corn", "cornmeal", "corn on the cob", "meal"),则计数将为3。
发布于 2011-10-16 11:41:35
让我们暂时假设您想要包含“corn”的元素的数量:
length(grep("corn", dataset))
[1] 3在更好地理解R的基础知识之后,您可能想看看"tm“包。
编辑:我知道这一次你想要任何-“玉米”,但在未来你可能想要“玉米”这个词。比尔·邓拉普在r-help上指出了一种更紧凑的grep模式,用于收集完整的单词:
grep("\\<corn\\>", dataset)发布于 2013-03-12 16:43:40
另一种非常方便和直观的方法是使用stringr包的str_count函数:
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发布于 2017-12-02 20:48:35
您还可以执行以下操作:
length(dataset[which(dataset=="corn")])https://stackoverflow.com/questions/7782113
复制相似问题