10

If I have a run of characters such as "AABBABBBAAAABBAAAABBBAABBBBABABB".

Is there a way to get R to count the runs of A and state how many of each length ?

So I'd like to know how many instances of 3 A's in a row, how many instances of a single A, how many instances of 2 A's in a row, etc.

4 Answers 4

11
table(rle(strsplit("AABBABBBAAAABBAAAABBBAABBBBABABB","")[[1]]))

gives

       values
lengths A B
      1 3 1
      2 2 3
      3 0 2
      4 2 1

which (reading down the A column) means there were 3 A runs of length 1, 2 A runs of length 2 and 2 A runs of length 4.

5
  • 2
    Speed wasn't mentioned as a primary consideration in the question, but there will be faster approaches.
    – Glen_b
    Jun 24, 2015 at 11:34
  • @akrun yes, rle is usually fast but strsplit can be slow.
    – Glen_b
    Jun 24, 2015 at 11:36
  • Yeah, I might use this one for its better output (on account of representing the differing strings by their lengths, and because I doubt speed matters). Or just table(nchar(strsplit(x, "[^A]+")[[1]])) since the OP only cares about "A".
    – Frank
    Jun 24, 2015 at 16:57
  • what is the [[1]] at the end doing ? Jun 25, 2015 at 10:51
  • strsplit returns a list (in this case, since the argument contained only one element, it returns, a list with one element, which contains a character vector that results from splitting it). I wanted the character vector rather than the list it was contained in; [[1]] is one way to achieve that.
    – Glen_b
    Jun 25, 2015 at 12:26
10

Try

 v1 <- scan(text=gsub('[^A]+', ',', str1), sep=',', what='', quiet=TRUE)
 table(v1[nzchar(v1)])
 # A   AA AAAA 
 # 3    2    2 

Or

 library(stringi)
 table(stri_extract_all_regex(str1, '[A]+')[[1]])
 # A   AA AAAA 
 # 3    2    2 

Benchmarks

 set.seed(42)
 x1 <- stri_rand_strings(1,1e7, pattern='[A-G]')

 system.time(table(stri_split_regex(x1, "[^A]+", omit_empty = TRUE)))
 #   user  system elapsed 
 #  0.829   0.002   0.831 

 system.time(table(stri_extract_all_regex(x1, '[A]+')[[1]]))
 #   user  system elapsed 
 #   0.790   0.002   0.791 

 system.time(table(rle(strsplit(x1,"")[[1]])) )
 #   user  system elapsed 
 #  30.230   1.243  31.523 

 system.time(table(strsplit(x1, "[^A]+")))
 # user  system elapsed 
 # 4.253   0.006   4.258 


 system.time(table(attr(gregexpr("A+",x1)[[1]], 'match.length')))
 #  user  system elapsed 
 #  1.994   0.004   1.999 


 library(microbenchmark)
 microbenchmark(david=table(stri_split_regex(x1, "[^A]+", omit_empty = TRUE)),
    akrun=  table(stri_extract_all_regex(x1, '[A]+')[[1]]),
    david2 =  table(strsplit(x1, "[^A]+")),
    glen = table(rle(strsplit(x1,"")[[1]])),
    plannapus = table(attr(gregexpr("A+",x1)[[1]], 'match.length')),
         times=20L, unit='relative')

#Unit: relative
#     expr       min        lq      mean    median         uq       max    neval  cld
#   david  1.0000000  1.000000  1.000000  1.000000  1.0000000  1.000000    20       a  
#   akrun  0.7908313  1.023388  1.054670  1.336510  0.9903384  1.004711    20       a
#  david2  4.9325256  5.461389  5.613516  6.207990  5.6647301  5.374668    20       c 
#    glen 14.9064240 15.975846 16.672339 20.570874 15.8710402 15.465140    20       d
#plannapus 2.5077719  3.123360  2.836338  3.557242  2.5689176  2.452964    20       b 

data

 str1 <- 'AABBABBBAAAABBAAAABBBAABBBBABABB'
14
  • The timings are interesting.
    – Glen_b
    Jun 24, 2015 at 11:38
  • @Glen_b I am running it again with the new post
    – akrun
    Jun 24, 2015 at 11:38
  • @akrun i don't think mine will fare particularly well in term of speed :)
    – plannapus
    Jun 24, 2015 at 11:39
  • @plannapus with stringi, it is hard to compete, but I will update just for making it complete
    – akrun
    Jun 24, 2015 at 11:40
  • @plannapus You are right. I tried microbenchmark, but I had to stop it as it is taking a long time. I am updating with the system.time
    – akrun
    Jun 24, 2015 at 13:13
8

Here's additional way using strsplit

x <- "AABBABBBAAAABBAAAABBBAABBBBABABB"
table(strsplit(x, "[^A]+"))
# A   AA AAAA 
# 3    2    2 

Or similarly with the stringi package

library(stringi)
table(stri_split_regex(x, "[^A]+", omit_empty = TRUE))
0
3

For completeness, here is another way, using the regmatches and gregexpr combo, to extract regexes:

x <- "AABBABBBAAAABBAAAABBBAABBBBABABB"
table(regmatches(x,gregexpr("A+",x))[[1]])
#   A   AA AAAA 
#   3    2    2

Or in fact, since gregexpr keeps the length of the captured substring as attribute, one could even do, directly:

table(attr(gregexpr("A+",x)[[1]],'match.length'))
# 1 2 4 
# 3 2 2 
3
  • I updated the benchmarks. Your version is faster among the base R functions
    – akrun
    Jun 24, 2015 at 14:54
  • I tried creating a random sample of 100 with replacement and as expected end up with a mix of "A"s and "B"s. I think in doing so I have created more problems as I now appear to have 100 individual strings. Was the a bad idea ? Jun 25, 2015 at 10:59
  • If you want to create a random sample of 100 A or Bs with replacement you might either use @akrun stringi-based technique (see his answer) or the base way: paste(sample(c("A","B"),100,replace=TRUE),collapse="")
    – plannapus
    Jun 25, 2015 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.