计算R中的单词出现次数

时间:2011-10-16 03:08:37

标签: string r

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

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

5 个答案:

答案 0 :(得分:34)

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

length(grep("corn", dataset))
[1] 3

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

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

grep("\\<corn\\>", dataset)

答案 1 :(得分:28)

另一种非常方便直观的方法是使用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

答案 2 :(得分:1)

您还可以执行以下操作:

length(dataset[which(dataset=="corn")])

答案 3 :(得分:0)

我只是用字符串除法来做到这一点,

library(roperators)

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

# for each vector element:
dataset %s/% 'corn'

# for everything:
sum(dataset %s/% 'corn') 

答案 4 :(得分:0)

您可以使用 stringr 包中的 str_count 函数来获取与给定字符向量匹配的关键字数。

str_count 函数的 pattern 参数接受可用于指定关键字的正则表达式。

正则表达式语法非常灵活,允许匹配整个单词和字符模式。

例如,以下代码将计算字符串“corn”的所有出现次数并返回 3:

sum(str_count(dataset, regex("corn")))

要匹配完整的单词,请使用:

sum(str_count(dataset, regex("\\bcorn\\b")))

"\b" 用于指定单词边界。使用 str_count 函数时,词边界的默认定义包括撇号。因此,如果您的数据集包含字符串“corn's”,它将被匹配并包含在结果中。

这是因为默认情况下撇号被视为单词边界。为防止计算包含撇号的单词,请使用参数 uword = T 的 regex 函数。这将导致正则表达式引擎使用 unicode TR 29 定义的单词边界。见http://unicode.org/reports/tr29/tr29-4.html。此定义未将撇号视为单词边界。

以下代码将给出单词“corn”出现的次数。将不包括“玉米”之类的词。

sum(str_count(dataset, regex("\\bcorn\\b", uword = T)))
相关问题