我正在尝试计算字符向量中子字符串的出现次数.例如:
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)返回:2 0 1
但是,我希望它返回 '3 0 1' 但它没有在第一项中的中间 'aba' 上找到,因为它在第一个实例中被部分使用(我认为).
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.
推荐答案尝试:
str_count(lookin, paste0("(?=",searchfor,")")) [1] 3 0 1正如您的链接中所回答的那样,使用前瞻来匹配所有实例.
Which, as answered in your link, uses lookahead to match all instances.