Find the longest sequential number in R
2 answers
One way is to split the vector into its sequences and then take the longest element in the list.
x <- c(1, 2, 10, 41, 42, 43, 50)
s <- split(x, cumsum(c(TRUE, diff(x) != 1)))
s[[which.max(sapply(s, length))]]
# [1] 41 42 43
Note that if anchored, the first longest set will be returned.
+5
source to share