title: Sequence length encoding using R
body: <p>Is there a way to encode <em>increasing integer sequences</em> in R, analogous to encoding run lengths using run length encoding (<code>rle</code>)?</p>
  
  <p>I'll illustrate with an example:</p>
  
  <p><strong>Analogy: Run length encoding</strong></p>
  
  <pre><code>r &lt;- c(rep(1, 4), 2, 3, 4, rep(5, 5))
  rle(r)
  Run Length Encoding
    lengths: int [1:5] 4 1 1 1 5
    values : num [1:5] 1 2 3 4 5
  </code></pre>
  
  <p><strong>Desired: sequence length encoding</strong></p>
  
  <pre><code>s &lt;- c(1:4, rep(5, 4), 6:9)
  s
  [1] 1 2 3 4 5 5 5 5 6 7 8 9
  
  somefunction(s)
  Sequence lengths
    lengths: int [1:4] 5 1 1 5
    value1 : num [1:4] 1 5 5 5
  </code></pre>
  
  <p><strong>Edit 1</strong></p>
  
  <p>Thus, <code>somefunction(1:10)</code> will give the result:</p>
  
  <pre><code>Sequence lengths
    lengths: int [1:1] 10
    value1 : num [1:1] 1 
  </code></pre>
  
  <p>This results means that there is an integer sequence of length 10 with starting value of 1, i.e. <code>seq(1, 10)</code></p>
  
  <p>Note that there isn't a mistake in my example result.  The vector in fact ends in the sequence 5:9, not 6:9 which was used to construct it.</p>
  
  <p>My use case is that I am working with survey data in an SPSS export file.  Each subquestion in a grid of questions will have a name of the pattern <code>paste("q", 1:5)</code>, but sometimes there is an "other" category which will be marked <code>q_99</code>, <code>q_other</code> or something else.  I wish to find a way of identifying the sequences.</p>
  
  <p><strong>Edit 2</strong></p>
  
  <p>In a way, my desired function is the inverse of the base function <code>sequence</code>, with the start value, <code>value1</code> in my example, added.</p>
  
  <pre><code>lengths &lt;- c(5, 1, 1, 5)
  value1 &lt;- c(1, 5, 5, 5)
  
  s
  [1] 1 2 3 4 5 5 5 5 6 7 8 9
  sequence(lengths) + rep(value1-1, lengths) 
  [1] 1 2 3 4 5 5 5 5 6 7 8 9
  </code></pre>
  
  <p><strong>Edit 3</strong></p>
  
  <p>I should have stated that for my purposes a sequence is defined as <strong>increasing integer sequences</strong> as opposed to monotonically increasing sequences, e.g. <code>c(4,5,6,7)</code> but not <code>c(2,4,6,8)</code> nor <code>c(5,4,3,2,1)</code>.  However, any other integer can appear between sequences.</p>
  
  <p>This means a solution should be able to cope with this test case:</p>
  
  <pre><code>somefunction(c(2, 4, 1:4, 5, 5))
      Sequence lengths
        lengths: int [1:4] 1 1 5 1
        value1 : num [1:4] 2 4 1 5 
  </code></pre>
  
  <p>In the ideal case, the solution can also cope with the use case suggested originally, which would include characters in the vector, e.g.</p>
  
  <pre><code>somefunction(c(2, 4, 1:4, 5, "other"))
      Sequence lengths
        lengths: int [1:5] 1 1 5 1 1
        value1 : num [1:5] 2 4 1 5 "other"
  </code></pre>