Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break up a vector into contiguous groups in R [duplicate]

Tags:

r

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.

like image 382
Alex Avatar asked Nov 23 '25 17:11

Alex


1 Answers

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.

like image 69
Gregor Thomas Avatar answered Nov 26 '25 06:11

Gregor Thomas