R Vij R Vij - 3 months ago 9
R Question

extracting exact number of rows from a list

A list of numbers like

a
1
2
3
6
7
8
9
10
11
12
15
16
19
20
21
22
23
24
25


To extract 3 continuous values without duplicates.
Result should be like

It is like making every 3 continuous rows to column but we can see 7,8,9 are also continuous but neglected to remove duplicates

a b c
1 2 3
6 7 8
9 10 11
19 20 21
22 23 24


Thanks in advance

Answer

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
Comments