我有一个如下的数字向量。
V1 <- c(1:3, 7:20, 23,45,55,27:30, 66, 88:89)
Run Code Online (Sandbox Code Playgroud)
如何找到最长的连续序列和位置?在这种情况下,所述靶序列的长度是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))
Run Code Online (Sandbox Code Playgroud)
但是我找不到 18
我们可以使用rle上diff的V1
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
Run Code Online (Sandbox Code Playgroud)