在 R 中按顺序查找开始和停止索引 [英] Finding the start and stop indices in sequence in R
本文介绍了在 R 中按顺序查找开始和停止索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下序列:
x = c( 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0)
在 R 中有没有一种优雅的方法来返回每个 1 序列的开始和停止索引?
Is there an elegant way in R to return the start and stop indices of each sequence of 1s?
答案应该是一个 2 列的数组,其中 nRows = 1 的序列数:
The answer should be a 2 column array with nRows = number of sequences of 1s:
startIndx = [ 1, 5, 7 ]
stopIndex = [ 2, 5, 9 ]
谢谢.
BSL
推荐答案
假设您的向量由 0 和 1 值组成:
Assuming your vector consists of 0 and 1 values:
which(diff(c(0L, x)) == 1L)
#[1] 1 5 7
which(diff(c(x, 0L)) == -1L)
#[1] 2 5 9
否则你首先需要像 x <- x == 1L
这样的东西.
Otherwise you'd need something like x <- x == 1L
first.
这篇关于在 R 中按顺序查找开始和停止索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文