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

标签 r

我有一个数字向量如下。

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/

相关文章:

r - 如何根据多面条形图的分类变量因子进行着色?

python - R 相当于 `python -i`

r - R : efficiently count number of edges between multiple sets of vertices 中的 igraph

r - 多个 selectInput 值会产生意外的 dplyr (postgres) 行为

r - 将数据框列表转换为具有列表名称的单个数据框

r - 如何在 R 中使用 read.excel() 指定列 as.factor ?

删除R中数据中不必要的符号

r - 筛选 Shiny R中的 react 数据集

r - 如果未找到某个分组中的值,我们如何才能将 count 设为 0,而不是在 data.table rollup 中完全删除该行?

r - 提高循环内 bind_rows 的速度(3000 个数据帧)