 <p>Try this:</p> <pre><code>tt &lt;- c(0, 1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4, 5) grp &lt;- cumsum(c(FALSE, diff(tt) &lt; 0)) </code></pre> <p>which gives:</p> <pre><code>&gt; grp [1] 0 0 0 0 0 0 1 1 1 1 2 2 2 2 2 </code></pre>