Split a numeric vector into continuous chunks in R

2019-05-26 15:17发布

问题:

This question already has an answer here:

  • Continuous integer runs 6 answers

If I have a numeric vector [1 2 3 4 7 8 9 10 15 16 17], how can I split it so that I have multiple vectors returned that separate the continuous elements of that vector? I.e. [1 2 3 4] [7 8 9 10] [15 16 17]. I've found an answer of how to do this in matlab, but I only use R.

Thanks.

回答1:

Here's another alternative:

vec <- c( 1, 2, 3, 4, 7, 8, 9, 10, 15, 16, 17 )
split(vec, cumsum(seq_along(vec) %in% (which(diff(vec)>1)+1)))
# $`0`
# [1] 1 2 3 4
# 
# $`1`
# [1]  7  8  9 10
# 
# $`2`
# [1] 15 16 17


回答2:

Another option:

split(vec, cummax(c(1,diff(vec))))

Result

$`1`
[1] 1 2 3 4

$`3`
[1]  7  8  9 10

$`5`
[1] 15 16 17


标签: r vector