What's a clever (i.e., not a loop) way to get the length of each spell of missing values in a vector? My ideal output is a vector that is the same length, in which each missing value is replaced by the length of the spell of missing values of which it was a part, and all other values are 0's.
So, for input like:
x <- c(2,6,1,2,NA,NA,NA,3,4,NA,NA)
I'd like output like:
y <- c(0,0,0,0,3,3,3,0,0,2,2)
One simple option using rle
:
m <- rle(is.na(x))
> rep(ifelse(m$values,m$lengths,0),times = m$lengths)
[1] 0 0 0 0 3 3 3 0 0 2 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With