DHWANI DHOLAKIA
DHWANI DHOLAKIA

Reputation: 53

How to find repetitive elements(substring) in a string in R

a <- "ABDBBBLKDLKFFABDBOKKKMXKMABDBLPDLABDBKMKNABDBLKMXLSKMABDBOKOLKABDB"

How to find how many times "ABDB" is repeated in a string?

Upvotes: 0

Views: 112

Answers (2)

RHertel
RHertel

Reputation: 23788

Here is a solution that neither requires a loop over the string nor an external package:

length(unlist(strsplit(paste0(a, "#"), "ABDB"))) - 1
#[1] 7

In this line of code, "#" is an auxiliary delimiter that is temporarily attached at the end of the string to make sure that occurrences of the pattern at the end are accounted for correctly.

Upvotes: 3

Rich Scriven
Rich Scriven

Reputation: 99331

stringi can do this very easily.

library(stringi)
stri_count_fixed(a, "ABDB")
# [1] 7

Upvotes: 4

Related Questions