4

I have a string that I've converted into a character vector:

string <- c("A","A","A","C","G","G","C","C","T","T","T","T")

I'd like to be able to output a table that shows the indices of the consecutive letters in the order they appear. for example:

letter start end
A 1 3
C 4 4
G 5 6
C 7 8
T 9 12

I've tried looking into str_locate and some other str functions but haven't been able to figure it out. Any help appreciated!

Beeba
  • 642
  • 1
  • 7
  • 18

2 Answers2

6

I will using cumsum after rle

s=rle(string)
v=cumsum(rle(string)$lengths)
data.frame('var'=s$values,'start'=v+1-s$lengths,'end'=v)
  var start end
1   A     1   3
2   C     4   4
3   G     5   6
4   C     7   8
5   T     9  12
BENY
  • 317,841
  • 20
  • 164
  • 234
3

We can use split by the run-length-id of 'string' into a list, get the range of values, and rbind the list elements

rl <- rle(string)
lst <- lapply(split(seq_along(string), rep(seq_along(rl$values), rl$lengths)), range)
names(lst) <- r1$values
do.call(rbind, lst)
#  [,1] [,2]
#A    1    3
#C    4    4
#G    5    6
#C    7    8
#T    9   12

Or in a compact way

library(data.table)
data.table(letter = string)[, .(letter = letter[1], start = .I[1],
               end = .I[.N]), rleid(letter)]

Or with tidyverse

library(tidyverse)
library(data.table)
string %>% 
   tibble(letter = .) %>% 
   mutate(rn = row_number()) %>%
   group_by(grp = rleid(letter)) %>% 
   summarise(letter = first(letter), 
             start = first(rn), 
             end = last(rn)) %>%
   ungroup %>% 
   select(-grp)
akrun
  • 874,273
  • 37
  • 540
  • 662