I have this vector
set.seed(234)
x <- sample(c(rep(NA,3),1:5))
x
[1] 3 5 NA 1 4 NA NA 2
For each NA
, I want the index (or value) of the last preceeding non-NA
value. That is, for the first NA
, the last previous non-NA
has the index 2. For the next two NA
, their last previous non-NA
has index 5:
[1] NA NA 2 NA NA 5 5 NA
Base R
or tidyverse
would be ok. I tried combinations of lag
, lead
, rle
, gl
& coalesce
, but all without success. For instance this which is pretty near, but still wrong.
a <- rle(is.na(x))
rep(1:length(a$lengths), a$lengths)
[1] 1 1 2 3 3 4 4 5