Here's a cumsum
"trick" for you:
split(vec, cumsum(c(1, diff(vec)) - 1))
update
Here is a simple example using your version split(vec, cumsum(c(0, diff(vec) > 1)))
with each step broken down:
vec <- c(1:3,7:9) # 1 2 3 7 8 9 (sample with two contiguous sequences)
diff(vec) # 1 1 4 1 1 (lagged difference)
diff(vec) > 1 # F F T F F (not contiguous where diff > 1)
# 0 0 1 0 0 (numeric equivalent for T/F)
c(0, diff(vec) > 1) # 0 0 0 1 0 0 (pad with 0 to align with original vector)
cumsum(c(0, diff(vec) > 1)) # 0 0 0 1 1 1 (cumulative sum of logical values)
groups <- cumsum(c(0, diff(vec) > 1)) # 0 0 0 1 1 1
sets <- split(vec, groups) # split into groups named by cumulative sum
sets
# $`0`
# [1] 1 2 3
#
# $`1`
# [1] 7 8 9
And then if you want to output it for some reason:
# Create strings representing each contiguous range
set_strings <- sapply(sets, function(x) paste0(min(x),":",max(x)))
set_strings
# 0 1
# "1:3" "7:9"
# Print out a concise representation of all contiguous sequences
print(paste0(set_strings,collapse=","))
# [1] "1:3,7:9"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…