1
votes

I've searched around but haven't been able to find a solution to my question yet. I'm not really sure where to start.

I have a numeric vector in R. For example:

vec<-c(8,1,2,5,20,1,6,7,13,1,8,1,14,1,1,4,2,7)

I'm looking to find the index where the value '1' occurs at least 3 times within a window of 5. So in the above example, the output would be '10' as the window containing '1,8,1,14,1' is the first sequence of 5 values where 3 values are '1' and the index of the start of that sequence is 10.

Any help would be appreciated.

3

3 Answers

1
votes

If you only want to get indeces, try using rollapply from zoo package as this:

> library(zoo)
> which(rollapply(vec, 5, FUN=function(x) sum(x==1)>=3))
[1] 10 11 12
1
votes

Try this one-liner. Note that each of the returned 3 indexes satisfy the condition.

library(zoo)

which(rollapply(vec, 5, function(x) sum(x == 1) >= 3, fill = FALSE, align = "left"))
## [1] 10 11 12
0
votes
vec<-c(8,1,2,5,20,1,6,7,13,1,8,1,14,1,1,4,2,7)

window=5
numberToFind=1
timesToFind=3
for(i in 1:(length(vec)-window+1)) {
    if(sum(vec[i:(i+window-1)] == numberToFind) == timesToFind) {
        print(i)
        break
    }
}