Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading