Increase counter upon change of value : <p>I made a function to increase a counter whenever the value in a vector changes:</p>

<pre><code>track_change = function(x) {
  counter = numeric(length(x))
  for (i in seq_along(x)) {
    if (i &gt; 1 &amp;&amp; x[i] != x[i-1])
      counter[i] = counter[i-1] + 1
    else if (i &gt; 1)
      counter[i] = counter[i-1]
  }
  counter
}
</code></pre>

<p>Example (see how <code>track</code> changes upon every change of <code>carb</code>):</p>

<pre><code>mtcars$track = track_change(mtcars$carb)

head(mtcars[, 10:12])
                  gear carb track
Mazda RX4            4    4     0
Mazda RX4 Wag        4    4     0
Datsun 710           4    1     1
Hornet 4 Drive       3    1     1
Hornet Sportabout    3    2     2
Valiant              3    1     3
</code></pre>

<p>Is there a better way to do this in R? (It should also be able to track changes in non-numerical vectors, incl. lists.)</p>
