Reputation: 35
Let's say I have a vector:
vec <- c(3,0,1,3,0,1,0,1,2,3,0,0,1,3,1,3)
I want to obtain the index of the first occurrence of 1 after every 3. So, the output of indices I want is
3,6,13,15
How would I do this in R?
Upvotes: 0
Views: 30
Reputation: 887223
We can also use rleid
library(data.table)
na.omit(as.vector(tapply(seq_along(vec) * (vec== 1), rleid(vec == 3), FUN = function(x)x[x > 0][1])))
#[1] 3 6 13 15
Upvotes: 0
Reputation: 24820
One approach would be to use cumsum
to keep track of 3s.
mat <- cbind(cumsum(vec==3), vec == 1)
which(!duplicated(mat) & mat[,2] & mat[,1] > 0)
[1] 3 6 13 15
Upvotes: 2