5

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
garson
  • 1,505
  • 3
  • 22
  • 56

1 Answers1

6

Try:

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

[1] 3 0 1

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

Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56