Find the longest sequential number in R
Hi I have a list of numbers like c (1,2,10,41,42,43,50). The length of the longest sequential strip will be 3 and it starts at 41. However, how can I implement it in R? Many thanks!
+3
user3446735
source
to share
2 answers
Here's one possible solution
v <- c(1,2,10,41,42,43,50) # Your data
temp <- cumsum(c(1, diff(v) - 1))
temp2 <- rle(temp)
v[which(temp == with(temp2, values[which.max(lengths)]))]
# [1] 41 42 43
+7
David Arenburg
source
to share
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
Rich scriven
source
to share