Finding the longest stretch of repeated words in a long string of characters

Viewed 80

I have a long DNA sequence text file with characters (ATCG). I am looking for some method in R that can be used to find the longest stretch with repeated words. Lets say my string looks like, AAGTGCGGGTTCAGATCGCCCCCCCATCGGGCAAAAAAAAAAAAAAAATCGA

I need the output possibly with counts, AAAAAAAAAAAAAAAA n=16

Please help me with this.

4 Answers

if you have one string:

library(tidyverse)
string <- "AAGTGCGGGTTCAGATCGCCCCCCCATCGGGCAAAAAAAAAAAAAAAATCGA"

x <- str_extract_all(string, "(.)\\1+")
x[which.max(nchar(x))]

[1] "AAAAAAAAAAAAAAAA"

if you have many strings:

str_extract_all(c(string, string), "(.)\\1+")%>%
  map_chr(~.x[which.max(nchar(.x))])

[1] "AAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAA"

To find the counts, just use nchar or even str_count of the result

Another possible solution:

library(tidyverse)

s <- "AAGTGCGGGTTCAGATCGCCCCCCCATCGGGCAAAAAAAAAAAAAAAATCGA"

data.frame(seq = str_extract_all(s, "([A-Z])\\1{2,}") %>% unlist) %>% 
  mutate(n = str_count(seq)) %>% 
  slice_max(n, n = 1)

#>                seq  n
#> 1 AAAAAAAAAAAAAAAA 16

Perhaps you can try this

> s <- "AAGTGCGGGTTCAGATCGCCCCCCCATCGGGCAAAAAAAAAAAAAAAATCGA"

> v <- regmatches(s, gregexpr("(.)\\1+", s))[[1]]

> v[which.max(nchar(v))]
[1] "AAAAAAAAAAAAAAAA"

First form a vector of all same base pair substrings. Then, find the longest string in that vector.

x <- "AAGTGCGGGTTCAGATCGCCCCCCCATCGGGCAAAAAAAAAAAAAAAATCGA"
parts <- unlist(strsplit(x, "(?<=([ACGT]))(?!\\1)"))
parts[order(-nchar(parts), parts)][1]

[1] "AAAAAAAAAAAAAAAA"
Related