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.
Here is an example of what I've tried:
require(dplyr)
df <- data.frame(fac = rep(c("A", "B", "C"), 3))
for(i in levels(fac)){
if(i != levels(fac)[length(levels(fac))]){
df %>% filter(fac %in% c(i, i + 1))
}
}
I try to have level i
and its subsequent level included but obviously expression i + 1
won't do the trick. How to get around this? Do I have to make variable fac
numerical or is there a neater solution available?
EDIT: The output (for this example) should be these two data.frames:
dfAB <- df %>% filter(fac %in% c("A", "B"))
dfBC <- df %>% filter(fac %in% c("B", "C"))