什么是计算另一个字符串出现次数的最简单方法?

时间:2014-10-29 20:40:11

标签: r

这就是我所知道的,即我打算在该字符串中获取换行次数:

> res <- grep("\n","why \n is this not \n easier?")
> str(res)
  int 1
> res
[1] 1
> 

我想要做的是获得实际的2而不是1.是否有另一种方式,最好不使用第三方包(需要检查我的依赖性足迹)。

更新:使用MrFlick解决方案作为灵感,我最终做了:

countOccurrences <- function(pattern, x) {
    return(ifelse(grepl(pattern, x), sapply(gregexpr(pattern, x), length), 0))
}

> countOccurrences("\n", "why \n is this not \n easier?")
[1] 2
> countOccurrences("\n", "why is this not easier?")
[1] 0
> countOccurrences("\n", "why \n is \n this \n not \n easier? \n")
[1] 5
> 

2 个答案:

答案 0 :(得分:3)

你可以做到

test <- c("why \n is this not \n easier?", "none","just\none","\n\n")
res <- gregexpr("\n",test)
sapply(res, function(x) sum(x>=0))
# [1] 2 0 1 2

我们在这里使用gregexpr,因为grep只会匹配第一次出现。另外我们申请我们应用一个函数来计算匹配位置的数量(忽略-1,不匹配)

答案 1 :(得分:3)

我知道你提到你不想使用包,但包stringi非常有效。

library(stringi)
stri_count("why \n is this not \n easier?", fixed = "\n")
# [1] 2

如果字符串不包含匹配项,stri_count将返回零

stri_count("why is this not easier?", fixed = "\n")
# [1] 0
相关问题