0

How can I make a range of the ID of data while they are in sequence, for example: I have this

ID<-c(1,2,3,4,8,9,10,14,18,19,20,28,33,34,35,36,40,42,43,44,55,56)

I want it to count or make a range of the IDs that are in sequence series

my preferable output would be something like that

RANGE 1:4, 8:10, 14, 18:20, 28, 33:36, 40, 42:44, 55:56
NEW ID 1     2    3     4    5     6    7    8     9
markus
  • 25,843
  • 5
  • 39
  • 58

1 Answers1

4

Use split with diff to divide ID into groups.

result <- split(ID, cumsum(c(1, diff(ID) > 1)))
result
#$`1`
#[1] 1 2 3 4

#$`2`
#[1]  8  9 10

#$`3`
#[1] 14

#$`4`
#[1] 18 19 20

#$`5`
#[1] 28

#$`6`
#[1] 33 34 35 36
#...
#...

If you need output as a dataframe you can use stack(result) for it.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • maybe you can tell me how also to keep every time the first row of each changing? More specific I want to have the [1] 1, [2] 8, [3] 14, [4] 18 [5] 28 [6] 33 etc and also the last one of each changing such as [1] 4, [2] 10, [3] 14, [4] 20, [5] 28, [6] 36 etc – Maria Provelegiou Feb 25 '21 at 13:12
  • `sapply(result, head, 1)` and `sapply(result, tail, 1)` should give you that. – Ronak Shah Feb 25 '21 at 13:20
  • It is a great proposition but it does not work for my data set. I have a huge data frame and now my first column is the 1,1,1,1,2,2,2,3,3,3,3 etc and now i want to keep the first element of each changing of this column but keeping also the rows in my data set – Maria Provelegiou Feb 25 '21 at 13:38
  • In that case probably it is better to ask it as new question. – Ronak Shah Feb 25 '21 at 13:40