简体   繁体   English

获取第1个第1次和第2次出现之间的向量索引

[英]Get index of vector between 1nd and 2nd appearance of number 1

Suppose we have a vector: 假设我们有一个向量:

v <- c(0,0,0,1,0,0,0,1,1,1,0,0)

Expected output: 预期产量:

v_index <- c(5,6,7)

v always starts and ends with 0 . v始终以0开始和结束。 There is only one possibility of having cluster of zeros between two 1 s. 在两个1秒之间只有一个零簇的可能性。

Seems simple enough, can't get my head around... 看似简单,无法理解我的头脑......

I think this will do 我认为这样做

which(cumsum(v == 1L) == 1L)[-1L]
## [1] 5 6 7

The idea here is to separate all the instances of "one"s to groups and select the first group while removing the occurrence of the "one" at the beginning (because you only want the zeroes). 这里的想法是将“one”的所有实例分成组并选择第一组,同时在开头删除“one”的出现(因为你只想要零)。

v <- c(0,0,0,1,0,0,0,1,1,1,0,0)
v_index<-seq(which(v!=0)[1]+1,which(v!=0)[2]-1,1)


> v_index
[1] 5 6 7

Explanation:I ask which indices are not equal to 0: 说明:我问哪些索引不等于0:

which(v!=0)

then I take the first and second index from that vector and create a sequence out of it. 然后我从该向量中获取第一个和第二个索引,并从中创建一个序列。

This is probably one of the simplest answers out there. 这可能是最简单的答案之一。 Find which items are equal to one, then produce a sequence using the first two indexes, incrementing the first and decrementing the other. 找到哪些项等于1,然后使用前两个索引生成序列,递增第一个并递减另一个。

block <- which(v == 1)
start <- block[1] + 1
end <- block[2] - 1
v_index <- start:end
v_index
[1] 5 6 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM