2

I was wondering if there is a package or generic function in R that counts sequence lengths. For instance, if I input a sequence

s1<-c('a','a','b','a','a','a','b','b')

The proposed function F(s1,'a') would return a vector: [2,3] and F(s1,'b') would return [1,2]

g g
  • 87
  • 1
  • 5
  • 4
    Several people are currently madly typing as fast as they can to tell you about `rle`. – joran Mar 07 '12 at 23:26
  • perfect, I should have remembered that. Thanks. – g g Mar 07 '12 at 23:31
  • 1
    Several of us have written `seqle` which can search for either repetitions or sequences. For example: http://stackoverflow.com/questions/8400901/detect-intervals-of-the-consequent-integer-sequences – Carl Witthoft Mar 08 '12 at 02:25
  • +1. I'm surprised this question wasn't upvoted before. It just saved me from posting a question and/or spending hours of work. I'd never heard about this function. – Frank May 24 '13 at 17:24

1 Answers1

4

Those madly typing people must have gone elsewhere:

 s1<- c('a','a','b','a','a','a','b','b')
 F1 <- function(s, el) {rle(s)$lengths[rle(s)$values==el] }
 F1(s1, "a")
#[1] 2 3
 F1(s1, "b")
#[1] 1 2
IRTFM
  • 258,963
  • 21
  • 364
  • 487