首页 > 解决方案 > 为什么 str_count 不能处理多个字符串?

问题描述

我有一个带有这样文本的字符串:

Text <- c("How are you","What is your name","Hi my name is","You ate your cake")

我想要一个输出来计算单词“you”或“your”出现的次数

Text                   NumYou
"How are you"          1
"What is your name"    1
"Hi my name is"        0
"You ate your cake"    2

我尝试使用 str_count 函数,但它缺少“you”和“your”的出现

NumYou = str_count(text,c("you","your"))

为什么 str_count 不能正常工作?

标签: rstringsubstr-count

解决方案


pattern作为一个字符串传递。

stringr::str_count(tolower(Text),'you|your')
#[1] 1 1 0 2

推荐阅读