简体   繁体   中英

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 . There is only one possibility of having cluster of zeros between two 1 s.

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).

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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