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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With