gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:01:28 24 4
gpt4 key购买 nike

我知道为了计算一个子字符串的出现次数,我可以使用 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)
}
现在, ocurrences(string = "MSAGARRRPR", pattern = "RR")返回预期答案:2
尽管如此,我想知道是否有更有效的 R 函数来计算它。
提前致谢!

最佳答案

您可以使用lookbehind或lookahead正则表达式:
积极回顾:

stringr::str_count(string = "MSAGARRRPR", pattern = "(?<=R)R")
#[1] 2

stringr::str_count(string = "MSAGARRRPRR", pattern = "(?<=R)R")
#[1] 3
这也可以用积极的前瞻来写
stringr::str_count(string = "MSAGARRRPR", pattern = "R(?=R)")
#[1] 2

stringr::str_count(string = "MSAGARRRPRR", pattern = "R(?=R)")
#[1] 3

关于r - 是否有用于计算字符串中给定子字符串出现次数的 R 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65978370/

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