gpt4 book ai didi

r - 如何找到最长的连续数及其位置?

转载 作者:行者123 更新时间:2023-12-04 10:43:20 24 4
gpt4 key购买 nike

我有一个数字向量如下。

V1 <- c(1:3, 7:20, 23,45,55,27:30, 66, 88:89)

如何找到最长的连续序列和位置?在这种情况下,目标序列的长度为14,位置为18请指教

我丑陋的是使用whichshift

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的位置

最佳答案

我们可以在 V1diff 上使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com