title: Assign a group number based on another column by group in R
body: <p>This is probably very straight forward, but I can't figure out a way to do this. I have some data that looks like this: </p>
  
  <pre><code>domain  difference
  xxxx    0
  xxxx    2
  xxxx    14
  xxxx    3
  xxxx    7
  xxxx    2
  yyyy    6
  yyyy    5
  yyyy    13
  yyyy    10
  zzzz    2
  zzzz    5
  zzzz    1
  zzzz    15
  zzzz    16
  zzzz    8
  zzzz    9
  </code></pre>
  
  <p>I want it to look like this:</p>
  
  <pre><code>domain  difference  grp
  xxxx    0           1
  xxxx    2           1
  xxxx    14          2
  xxxx    3           2
  xxxx    7           2
  xxxx    2           2
  yyyy    6           1
  yyyy    5           1
  yyyy    13          1
  yyyy    10          1
  zzzz    2           1
  zzzz    5           1
  zzzz    1           1
  zzzz    15          2
  zzzz    16          3
  zzzz    8           3
  zzzz    9           3
  </code></pre>
  
  <p>So basically by domain I want to assign a group number to several rows if the difference is greater than or equal to 14. When there is a difference greater than or equal to 14, assign a group number to the previous rows. </p>
  
  <p>I've tried using a nested for loop, where the domains are levels but I feel like that may be unnecessarily complex, and I'm not sure how to tell the loop to keep going and pick up where it left off after assigning the first group number. Here's what I have so far:</p>
  
  <pre><code>lev &lt;- levels(e_won$domain)
  lev &lt;- levels(e_won$domain)
  for (i in 1:length(lev)) { 
    for (j in 1:nrow(lev)){
      if (difference[j] &gt;= 14) {
        grp[1:j] = 1
      }
  </code></pre>
  
  <p>I'm completely open to a non-loop solution, but that's just what I thought at first. </p>