A function for replacing each NA with the most recent non-NA prior to it.
na_locf(x, first_na_value = 0, recursive = TRUE, ...)
https://stat.ethz.ch/pipermail/r-help/2003-November/042126.html https://stackoverflow.com/questions/5302049/last-observation-carried-forward-na-locf-on-panel-cross-section-time-series
This could probably be solved MUCH faster using Rcpp.
The original vector, but with all the missing values filled by the value before them.
na.locf
na_locf(c(NA, NA))
#> [1] 0 0
na_locf(c(1, NA))
#> [1] 1 1
na_locf(c(1, NA, NA, NA))
#> [1] 1 1 1 1
na_locf(c(1, NA, NA, NA, 2, 2, NA, 3, NA, 4))
#> [1] 1 1 1 1 2 2 2 3 3 4
na_locf(c(1, NA, NA, NA, 2, 2, NA, 3, NA, 4), recursive = FALSE)
#> [1] 1 1 NA NA 2 2 2 3 3 4
if (FALSE) { # \dontrun{
# library(microbenchmark)
# library(zoo)
# microbenchmark(
# na_locf = na_locf(c(1, NA, NA, NA, 2, 2, NA, 3, NA, 4)),
# na.locf = na.locf(c(1, NA, NA, NA, 2, 2, NA, 3, NA, 4))
#) # my implementation is 6 times faster :)
#microbenchmark(
# na_locf = na_locf(rep(c(1, NA, NA, NA, 2, 2, NA, 3, NA, 4), 1000)),
# na.locf = na.locf(rep(c(1, NA, NA, NA, 2, 2, NA, 3, NA, 4), 1000))
# ) # my implementation is 3 times faster
} # }