title: Special occurrency counting in data table
body: <p>(preamble)
  I don't know if this is the right place for that...I actually have a problem solving/optimization issue for the counting over a table. So if it's not. very sorry and deserve the minusrating.</p>
  
  <p>Here's the data frame</p>
  
  <pre><code>dat &lt;- data.frame(id=letters[1:5],matrix(c(0,0,1,0,0,  0,1,0,1,1,  0,0,2,1,0, 1,0,2,1,1, 0,0,2,0,0, 0,1,2,1,0),5,6)) 
  
  # 
  #    id X1 X2 X3 X4 X5 X6 
  # 1  a  0  0  0  1  0  0 
  # 2  b  0  1  0  0  0  1
  # 3  c  1  0  2  2  2  2
  # 4  d  0  1  1  1  0  1 
  # 5  e  0  1  0  1  0  0 
  </code></pre>
  
  <p>I would like to count along every row, how many times we get to 1 and how many times from 1 we go to 0. so the final results should be </p>
  
  <pre><code># id N1 N0 
  # a  1  1 
  # b  2  1 
  # c  1  1 
  # d  2  1 
  # e  2  2 
  </code></pre>
  
  <p>I actually found an algorithm but it's more C/FORTRAN style (here below) and I can't believe there's not an esaier and more elegant way to get this in R. Thanks a lot for any help or hint. </p>
  
  <pre><code>nr &lt;- nrow(dat) 
  nc &lt;- ncol(dat) 
  rownames(dat) &lt;- seq(1,nr,1) 
  colnames(dat) &lt;- seq(1,nc,1) 
  dat$N1 &lt;- NULL 
  dat$N2 &lt;- NULL 
  for (i in 1:nr) { 
    n1 &lt;- 0 
    n0 &lt;- 0 
    j &lt;- 2 
    while (!(j&gt;nc)) { 
      k &lt;- j 
      if (dat[i,k] == 1) { 
        n1 &lt;- n1 + 1 
        k &lt;- j + 1 
        while (!(k&gt;nc)) { 
          if (dat[i,k] == 0) { 
            n0 &lt;- n0 + 1 
            break 
          } 
          k &lt;- k + 1 
        } 
      } 
      j &lt;- k 
      j &lt;- j + 1 
    } 
    dat$N1[i] &lt;- n1 
    dat$N0[i] &lt;- n0 
  }
  </code></pre>