如何在R中找到一个字符中的字符串

3

我知道这是一个非常幼稚的问题,但是我尝试了很多次,却没有找到一种在R中计算指定子字符串在字符字符串中出现次数的方法。

例如:

str <- "Hello this is devavrata! here, say again hello"

现在我想找到“hello”的出现次数(不区分大小写)。在这个例子中,答案应该是2。
编辑:我想知道当我查找“ello th”时,“str_count”会给出1次出现,但我想要被空格包围的确切单词出现的次数,也就是在这种情况下应该给出0次。例如,如果我想在特定的字符串中查找“very good”,如:

It is very good to speak like thevery good

这里出现次数应该为1而不是2。希望你明白。


你能把它展示在一个 string 中并展示你期望的结果吗? - akrun
我进行了一些更新,请检查是否有所帮助。 - akrun
3个回答

4
您可以尝试以下方法:
 library(stringi)
  stri_count(str, regex="(?i)hello")
  #[1] 2


  str1 <- "It is very good to speak like thevery good"
  stri_count(str1, regex="\\b(?i)very good\\b")
 #[1] 1

我在想当我找到ello th时,str_count会给出1的出现次数,但我想要精确的被空格包围的单词出现次数,也就是在这种情况下它应该给出 - Devavrata
谢谢,它运行得很好!stringi包需要加载lattice包吗? - Devavrata
@Devavrata 我不知道它是否需要格点作为依赖项,但有一件事是它在这些操作中非常快。 - akrun

2
也许最简单和直接的方法是使用来自 stringrstr_count
str <- "Hello this is devavrata! here, say again hello"
library(stringr)
str_count(str, ignore.case("hello"))
# [1] 2

两种基本的R方法是

length(grep("hello", strsplit(str, " ")[[1]], ignore.case = TRUE))
# [1] 2

并且

sum(gregexpr("hello", str, ignore.case = TRUE)[[1]] > 0)
# [1] 2

谢谢...我已经尝试了grep,但是当我需要查找像"very good"这样的字符串时,它会出错,这就是我面临的主要问题。 - Devavrata
@Devavrata - 字符串匹配非常具体,因此需要根据不同的匹配标准进行调整。 - Rich Scriven
准确地说,在我的计划中,这是主要问题,但是通过str_count已经解决了。我不想将我的字符串分成向量。 - Devavrata

2

我来晚了,但是我认为 qdap 包中的 termco 函数恰好符合您的要求。您可以使用前导和/或尾随空格来控制单词边界,如下面的示例所示:

x <- c("Hello this is devavrata! here, say again hello",
    "It is very good to speak like thevery good")

library(qdap)
(out <- termco(x, id(x), list("hello", "very good", " very good ")))

##   x word.count     hello very good very good
## 1 1          8 2(25.00%)         0         0
## 2 2          9         0 2(22.22%) 1(11.11%)

## To get a data frame of pure counts:
out %>% counts()

##   x word.count hello very good very good
## 1 1          8     2         0         0
## 2 2          9     0         2         1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接