[Solved] extracting exact number of rows from a list [closed]


A bit untidy, but does the job:

d <- data.frame(a=a[-(1:2)], diff=diff(a, 2))
d$br <- 0
for (i in 1:nrow(d)) {
  if (i==1 & d$diff[1]==2) {
    d$br[1] <- 1
  } else if (i==2 & d$diff[2]==2 & d$br[1]!=1) {
    d$br[2] <- 1
  }
  if (d$diff[i]==2 & !any(sum(d$br[c(i-1, i-2)])>0)) d$br[i] <- 1
}
t(sapply(d$a[d$br==1], function(x) (x-2):x))
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    6    7    8
# [3,]    9   10   11
# [4,]   19   20   21
# [5,]   22   23   24

Wrapping all that into a function, and testing with another sequence:

getConsec <- function(a) {
    d <- data.frame(a=a[-(1:2)], diff=diff(a, 2))
    d$br <- 0
    for (i in 1:nrow(d)) {
      if (i==1 & d$diff[1]==2) {
        d$br[1] <- 1
      } else if (i==2 & d$diff[2]==2 & d$br[1]!=1) {
        d$br[2] <- 1
      }
      if (d$diff[i]==2 & !any(sum(d$br[c(i-1, i-2)])>0)) d$br[i] <- 1
    }
    t(sapply(d$a[d$br==1], function(x) (x-2):x))
}

a <- sort(sample(1:30, 20))
 # [1]  1  2  3  4  6 10 12 14 15 16 17 18 19 20 21 23 25 27 28 30
getConsec(a)
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]   14   15   16
# [3,]   17   18   19

4

solved extracting exact number of rows from a list [closed]