小编eib*_*eib的帖子

是否有 R 函数用于计算字符串中给定子字符串的出现次数?

我知道为了计算一个子字符串的出现次数,我可以使用str.count()。然而这个功能不符合我的需求。更具体地说,假设我有字符串“MSAGARRRPR”,我想计算子字符串“RR”出现的次数。

stringr::str_count(string = "MSAGARRRPR", pattern = "RR")

将返回数字 1。但是,在当前示例中,我感兴趣的是计算“R”后面跟着另一个“R”的次数,并且这种情况发生了两次。

我写了一个函数来计算它:

occurrences <- function(string, pattern){
     n <- nchar(patter)
     number_pieces <- (nchar(string) - (n - 1))
     pieces <- character(number_pieces)
     for (i in 1:number_pieces){
        pieces[i] <- substring(string, first = i, last = i + (n - 1))
     }
     output <- sum(pieces == pattern)
     return(output)
    }
Run Code Online (Sandbox Code Playgroud)

现在,ocurrences(string = "MSAGARRRPR", pattern = "RR")返回预期答案:2

尽管如此,我想知道是否有更有效的 R 函数来计算它。

提前致谢!

r

5
推荐指数
2
解决办法
558
查看次数

标签 统计

r ×1