gpt4 book ai didi

r - 计算单词出现的次数 (dplyr)

转载 作者:行者123 更新时间:2023-12-03 08:59:29 26 4
gpt4 key购买 nike

这里是一个简单的问题,可能是 this 的重复项?

我试图弄清楚如何计算一个单词在向量中出现的次数。我知道我可以计算一个单词出现的行数,如下所示:

temp <- tibble(idvar = 1:3, 
response = (c("This sounds great",
"This is a great idea that sounds great",
"What a great idea")))
temp %>% count(grepl("great", response)) # lots of ways to do this line
# answer = 3

上面代码中的答案是 3,因为“great”出现在三行中。然而,“great”这个词在向量“response”中出现了 4 次不同的次数。我如何找到它?

最佳答案

我们可以使用 stringr 中的 str_count 来获取每行中具有“great”的实例数,然后获取其sum计数

library(tidyverse)
temp %>%
mutate(n = str_count(response, 'great')) %>%
summarise(n = sum(n))
# A tibble: 1 x 1
# n
# <int>
#1 4

或者使用base R中的regmatches/gregexpr

sum(lengths(regmatches(temp$response, gregexpr('great', temp$response))))
#[1] 4

关于r - 计算单词出现的次数 (dplyr),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52081181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com