【发布时间】:2021-11-17 15:23:45
【问题描述】:
是否有计算特定关键字包含在数据集中的次数的功能?
例如,如果dataset <- c("corn", "cornmeal", "corn on the cob", "meal"),则计数为 3。
【问题讨论】:
是否有计算特定关键字包含在数据集中的次数的功能?
例如,如果dataset <- c("corn", "cornmeal", "corn on the cob", "meal"),则计数为 3。
【问题讨论】:
让我们暂时假设您想要包含“玉米”的元素的数量:
length(grep("corn", dataset))
[1] 3
在您更好地了解 R 的基础知识后,您可能需要查看“tm”包。
编辑:我意识到这一次您想要任何-“玉米”,但将来您可能想要获得单词-“玉米”。在 r-help 上,Bill Dunlap 指出了一种更紧凑的 grep 模式来收集整个单词:
grep("\\<corn\\>", dataset)
【讨论】:
另一种非常方便直观的方法是使用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
【讨论】:
dataset <- c("corn corn", "cornmeal", "corn on the cob", "meal") 将返回 # [1] 2 1 1 0,而 grep 将始终返回 # [1] 1 1 1 0。 `
您还可以执行以下操作:
length(dataset[which(dataset=="corn")])
【讨论】:
我只是用字符串除法来做:
library(roperators)
dataset <- c("corn", "cornmeal", "corn on the cob", "meal")
# for each vector element:
dataset %s/% 'corn'
# for everything:
sum(dataset %s/% 'corn')
【讨论】:
您可以使用 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)))
【讨论】: