Home > Blockchain >  How to break up a vector into contiguous groups in R
How to break up a vector into contiguous groups in R

Time:08-10

I am curious if there is a functional way to break up a vector of contiguous groups in R.

For example if I have the following

# start with this
vec <- c(1,2,3,4,6,7,8,30,31,32)

# end with this
vec_vec <- list(c(1, 2, 3, 4),c(6,7,8),c(30,31,32))
print(vec_vec[1])

I can only imaging this is possible with a for loop where I calculate differences of previous values, but maybe there are better ways to solve this.

CodePudding user response:

split(vec, vec - seq_along(vec)) |> unname()
# [[1]]
# [1] 1 2 3 4
# 
# [[2]]
# [1] 6 7 8
# 
# [[3]]
# [1] 30 31 32

Subtratcing seq_along(vec) turns contiguous sequences into single values, which we can split by.

CodePudding user response:

1) The collapse package has seqid for this:

library(collapse)
split(vec, seqid(vec))

giving:

$`1`
[1] 1 2 3 4

$`2`
[1] 6 7 8

$`3`
[1] 30 31 32

2) A base approach is giving the same answer.

split(vec, cumsum(c(TRUE, diff(vec) != 1)))
  •  Tags:  
  • r
  • Related