title: r - Replace values in a data.frame column with a different value in the same column based unique ID
body: <p>I'm trying to loop through a column in a data.frame and replace 9's (invalid) with the next valid value not equal to 9 for each unique id in the data.frame. </p>
  
  <p>I've had no luck with <code>dplyr</code>, <code>lapply</code>, and I've been searching hard for similar problems to no avail.</p>
  
  <pre><code>#dummy data set
  id&lt;-c(1,1,1,1,2,2,2,2)
  ind&lt;-c(9,9,9,1,9,9,9,4)
  df&lt;-data.frame(id,ind)
  
  #unique doesn't get me what I want
  #If I do (i in 1:4) it will work for the first df$id but obviously not the 2nd.
  for (i in unique(length(df$id)))
    {
      j=df$ind!=9
      df$ind[i]&lt;-df$ind[j]
    }
  </code></pre>
  
  <p><code>unique length(df)</code> will not work, so I essentially can't get the loop to only apply to the subset of <code>df$id</code> values.  I think this will work if I can get past that.  Other non-loop solutions would be appreciated as well.    </p>