I want to split up my data into groups of successive rows that pass some test. Here's an example:
set.seed(1)
n <- 29
ok <- sample(c(TRUE,FALSE),n,replace=TRUE,prob=c(.7,.3))
vec <- (1:n)[ok]
# [1] 1 2 3 5 8 9 10 11 12 13 14 16 19 22 23 24 25 26 27 28
The desired output is "vec" grouped into contiguous sequences:
out <- list(1:3,5,8:14,16,19,22:28)
This works:
nv <- length(vec)
splits <- 1 + which(diff(vec) != 1)
splits <- c(1,splits,nv+1)
nsp <- length(splits)
out <- list()
for (i in 1:(nsp-1)){
out[[i]] <- vec[splits[i]:(splits[i+1]-1)]
}
I am guessing there is a cleaner way in base R...? I'm not yet adept with the rle
and cumsum
tricks I've seen on SO...