Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get length of runs of missing values in vector

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)
like image 776
daanoo Avatar asked Dec 13 '22 23:12

daanoo


1 Answers

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
like image 150
joran Avatar answered Dec 21 '22 22:12

joran