Search code examples
rrle

Identify first occurence of vector where 12 of 15 values are 1


I have a vector like so:

test = c(NA, 1, 1, 1, NA, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA, 1, 1, 1, 1, NA, NA, 1)

and within this vector I want to identify the first time that 12 of 15 values is equal to one.

I have started by using rle to count the consecutive values:

#get counts of sequences
count = rle(test)

and then getting a sequence based on this:

#make a sequence of the counts
new <- sequence(count$lengths) 

I will then turn any values in new to 0 where a test value is equal to NA:

#when the value was na make the count 0
new[is.na(test)] <- 0

and lastly I will change all other values to 1:

#make all other counts 1
new[new !=0] <- 1

which will return:

 [1] 0 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 0 1

this is where I am stuck, now I know the index location where the first time 12 out of 15 values is 1 is idx = 6, but I am stuck on how to retrieve it with an algorithm.


Solution

  • We could use rollapply to do the sum of logical vector, and get the index of first match where the sum is 12 with match

    library(zoo)
    match(12, rollapply(test, width = 15, FUN = function(x) sum(x== 1, na.rm = TRUE)))
    #[1] 6