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

63 Views Asked by At

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.

2

There are 2 best solutions below

0
akrun On BEST ANSWER

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
0
Allan Cameron On

We can use zoo::rollsum to find the first point where the next 15 values sum to 12 or more.

which(zoo::rollsum(test, 15, align = "left", fill = 0) >= 12)[1]
#> [1] 6

Created on 2020-07-17 by the reprex package (v0.3.0)