title: How can I rank observations in-group faster?
body: <p>I have a really simple problem, but I'm probably not thinking vector-y enough to solve it efficiently. I tried two different approaches and they've been looping on two different computers for a long time now. I wish I could say the competition made it more exciting, but ... bleh.</p>
  
  <h2>rank observations in group</h2>
  
  <p>I have long data (many rows per person, one row per person-observation) and I basically want a variable, that tells me how often the person has been observed already.</p>
  
  <p>I have the first two columns and want the <strong>third</strong> one:</p>
  
  <pre><code>person  wave   obs
  pers1   1999   1
  pers1   2000   2
  pers1   2003   3
  pers2   1998   1
  pers2   2001   2
  </code></pre>
  
  <p>Now I'm using two loop-approaches. Both are excruciatingly slow (150k rows). I'm sure I'm missing something, but my search queries didn't really help me yet (hard to phrase the problem).</p>
  
  <p>Thanks for any pointers!</p>
  
  <pre><code># ordered dataset by persnr and year of observation
  person.obs &lt;- person.obs[order(person.obs$PERSNR,person.obs$wave) , ]
  
  person.obs$n.obs = 0
  
  # first approach: loop through people and assign range
  unp = unique(person.obs$PERSNR)
  unplength = length(unp)
  for(i in 1:unplength) {
     print(unp[i])
     person.obs[which(person.obs$PERSNR==unp[i]),]$n.obs = 
  1:length(person.obs[which(person.obs$PERSNR==unp[i]),]$n.obs)
      i=i+1
     gc()
  }
  
  # second approach: loop through rows and reset counter at new person
  pnr = 0
  for(i in 1:length(person.obs[,2])) {
    if(pnr!=person.obs[i,]$PERSNR) { pnr = person.obs[i,]$PERSNR
    e = 0
    }
    e=e+1
    person.obs[i,]$n.obs = e
    i=i+1
    gc()
  }
  </code></pre>