str_count with overlapping substrings

假如想象 提交于 2019-12-07 04:56:16

问题


I am trying to count the number of appearances of a substring within a character vector. For example:

lookin<-c("babababa", "bellow", "ra;baba")
searchfor<-"aba"
str_count(lookin, searchfor)

returns: 2 0 1

However, I want it to return '3 0 1' but it isn't picking up on the middle 'aba' in the first item since it is partially used in the first instance (I think).

I found this question but couldn't figure out how to use that with a vector having multiple items.


回答1:


Try:

str_count(lookin, paste0("(?=",searchfor,")"))

[1] 3 0 1

Which, as answered in your link, uses lookahead to match all instances.



来源:https://stackoverflow.com/questions/31609721/str-count-with-overlapping-substrings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!