- A+

Category：Languages

Let's say I have a vector `x`

:

`x <- c(NA, NA, 1, 2, NA, NA, 3, 4) `

How do I identify sets of the NAs within this vector, i.e.,

`na_set <- c(1, 1, 0, 0, 2, 2, 0, 0) `

My end goal is to use it with a pipe on a data frame using `dplyr`

. So, if there's a function compatible with dplyr that's even better.

Thank you!

Compute the run length encoding of is.na(x) and replace the values with sequence numbers or 0. Then invert back.

`r <- rle(is.na(x)) r$values <- cumsum(r$values) * r$values inverse.rle(r) ## [1] 1 1 0 0 2 2 0 0 `