title: R: Produce Index Values to Group Increasing Values in Vector
body: <p>I have a list of increasing year values that occasionally has breaks in it and I want to create a grouping value for each unbroken sequence.  Think of a vector like this one (missing 2005,2011):</p>
  
  <pre><code>x &lt;- c(2001,2002,2003,2004,2006,2007,2008,2009,2010,2013,2014,2015,2016)
  </code></pre>
  
  <p>I would like to produce an equal length vector that numbers every value in a run with the same index to end up with something like this.</p>
  
  <pre><code>[1] 1 1 1 1 2 2 2 2 2 3 3 3 3
  </code></pre>
  
  <p>I would like to do this using best R practices so I am trying to avoid falling back to a for loop but I am not sure how to get from Vector A to Vector B.  Does anyone have any suggestions?  </p>
  
  <p>Some things I know I can do:</p>
  
  <ul>
  <li>I can flag the record before or after a gap as true with an ifelse</li>
  <li>I can get the index of when the counter should change by wrapping that in a which statement</li>
  </ul>
  
  <p>This is the code to do each</p>
  
  <pre><code>ifelse(!is.na(lag(x)) &amp; x == lag(x)+1, FALSE, TRUE)
  
  which(ifelse(!is.na(lag(x)) &amp; x == lag(x)+1, FALSE, TRUE))
  </code></pre>