 <p>Dplyr is much more intuitive and easy in my opinion. Using it here, you can do something like this:</p> <pre><code>library(dplyr) &gt; zzz &lt;- data.frame(name=rep(c('x','y','z'),100),balance=sample(100:300,100,replace = T)) &gt; zzz &lt;- arrange(zzz, name) &gt; zzz[5:7,2] &lt;-238 &gt; zzz[20:22,2]&lt;- 204 &gt; zzz &lt;- zzz %&gt;% group_by(name) %&gt;% mutate(code = as.numeric(balance != lag(balance))) &gt; zzz[5:7, ] Source: local data frame [3 x 3] Groups: name [1] name balance code (fctr) (dbl) (dbl) 1 x 238 1 2 x 238 0 3 x 238 0 &gt; zzz[20:22, ] Source: local data frame [3 x 3] Groups: name [1] name balance code (fctr) (dbl) (dbl) 1 x 204 1 2 x 204 0 3 x 204 0 &gt; </code></pre>