I have a vector in R that looks like this:
dat <- c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE)
What I would like to calculate is the distance between a particular value and the subsequent occurrence of the same value. In the example I look for the subsequent occurrence of “TRUE” and I would like the resulting vector to be:
dat1 <- c(1, 3, NA, NA, NA, NA)
Is there an easy way to do this?
Why the NA values at the end?
You can get -in this case- the correct answer by:
or, for the FALSE values :
You can then add as many NA values as you like, or predefine a vector, eg :