title: Looping over factor levels in R - how to operate two consecutive levels
body: <p>I need to loop over factor levels in an R data.frame. Inside the loop I need to do operations for data.frames that include subsets defined by pairs of these levels. The pairs are two consecutive unique levels of that factor.</p>
  
  <p>Here is an example of what I've tried:</p>
  
  <pre><code>require(dplyr)
  
  df &lt;- data.frame(fac = rep(c("A", "B", "C"), 3))
  
  for(i in levels(fac)){
  
     if(i != levels(fac)[length(levels(fac))]){
        df %&gt;% filter(fac %in% c(i, i + 1))
     }
  }
  </code></pre>
  
  <p>I try to have level <code>i</code> and its subsequent level included but obviously expression <code>i + 1</code> won't do the trick. How to get around this? Do I have to make variable <code>fac</code> numerical or is there a neater solution available?</p>
  
  <p>EDIT: The output (for this example) should be these two data.frames:</p>
  
  <pre><code>dfAB &lt;- df %&gt;% filter(fac %in% c("A", "B"))
  dfBC &lt;- df %&gt;% filter(fac %in% c("B", "C"))
  </code></pre>