Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of vector between 1nd and 2nd appearance of number 1

Tags:

r

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 1s.

Seems simple enough, can't get my head around...

like image 825
zx8754 Avatar asked Dec 02 '22 17:12

zx8754


2 Answers

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

like image 186
David Arenburg Avatar answered Mar 01 '23 23:03

David Arenburg


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.

like image 31
maRtin Avatar answered Mar 02 '23 00:03

maRtin