title: How to use an index within another index to locate a change in a variable - R
body: <p>I have the following dataset.</p>
  <pre><code>id&lt;-c(1001,1001,1001,1002,1002,1003,1004,1005,1005,1005)
  year&lt;-c(2010,2013,2016, 2013,2010,2010,2016,2016,2010,2013)
  status&lt;-c(2,2,2,3,4,2,1,1,1,5)
  df&lt;-data.frame(id, year, status)
  df &lt;- df[order(df$id, df$year), ]
  </code></pre>
  <p>My goal is to create a for-loop with two indices one for <code>id</code> and the other for <code>year</code> so that it runs through the <code>id</code> first and then within each <code>id</code> it looks at <code>years</code> in which there was a change in the <code>status</code>. To record the changes with this loop, I want another variable that shows in which the change happened.
  For example, in the dataframe below the variable <code>change</code> records 0 for <code>id</code> 1001 in all three years. But for 1002, a change in status is recorded with 1 in year 2013. For 1005, status changes twice, in 2013 and 2016, that's why 1 is recorded twice. btw, id is a character variable because the real data I am working on has alpha-numeric ids.</p>
  <pre><code>     id year status change
  1  1001 2010      2   0
  2  1001 2013      2   0
  3  1001 2016      2   0
  5  1002 2010      4   0
  4  1002 2013      3   1
  6  1003 2010      2   0
  7  1004 2016      1   0
  9  1005 2010      1   0
  10 1005 2013      2   1
  8  1005 2016      1   1
  </code></pre>
  <p>The actual dataframe has over 600k observations. Loop takes a lot of time running. I am open to faster solutions too.</p>
  <p>My code is below:</p>
  <pre><code>df$change&lt;-NA df$id&lt;-as.character(df$id) for(id in unique(df$id)) {
      tau&lt;-df$year[df$id==id]   if (length(tau)&gt;1) {
      for( j in 1:(length(tau)-1)){ 
        if (df$status[df$year==tau[j] &amp; df$id==id] != df$status[df$year==tau[j+1]&amp; df$id==id]) {
         df$change[df$year==tau[j]    &amp; df$id==id]&lt;-0
         df$change[df$year==tau[j+1]  &amp; df$id==id]&lt;-1
      } else {
         df$change[df$year==tau[j]    &amp; df$id==id]&lt;-0
         df$change[df$year==tau[j+1]  &amp; df$id==id]&lt;-0
      }}}
  </code></pre>