我有一个数字向量如下。
V1 <- c(1:3, 7:20, 23,45,55,27:30, 66, 88:89)
如何找到最长的连续序列和位置?在这种情况下,目标序列的长度为14
,位置为18
请指教
我丑陋的是使用which
和shift
V1 <- c(1:3, 7:20, 23,45,55,27:30, 66, 88:89)
V2 <- c(1, which(V1-shift(V1)!=1)
max(V2-shift(V2, fill =0))
但是我找不到18
的位置
最佳答案
我们可以在 V1
的 diff
上使用 rle
x <- rle(diff(V1))
#To get the length of longest sequence we can do
max(x$lengths) + 1
#[1] 14
#To get the end index of longest sequence
sum(x$lengths[seq_len(which.max(x$lengths))]) + 1
#[1] 17
关于r - 如何找到最长的连续数及其位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57676660/