Skip to content
Prev 378720 / 398502 Next

Replacing each NA with the most recent non-NA prior to it

If I use the na.locf function to replace each NA with the most recent
non-NA prior to it, then
[1] 1 1 1 4 4 2

I want to keep leading NA's, and this is what I want
 NA NA 1 4 4 2

How can I do it?

The following do not work:
Error in na.locf(c(NA, NA, 1, 4, NA, 2), na.rm = FALSE) :
  unused argument (na.rm = FALSE)
Error in na.locf(c(NA, NA, 1, 4, NA, 2), na.rm = TRUE) :
  unused argument (na.rm = TRUE)


Thank you very much!

John