xts method replace NA with most recent non-NA
# S3 method for class 'xts'
na.locf(object, na.rm = FALSE, fromLast = FALSE, maxgap = Inf, ...)An xts object.
Logical indicating whether leading/trailing NA should be
removed. The default is FALSE unlike the zoo method.
Logical indicating whether observations should be carried
backward rather than forward. Default is FALSE.
Consecutive runs of observations more than 'maxgap' will
remain NA. See na.locf() for details.
Unused.
An object where each NA in object is replaced by the most recent
non-NA prior to it. See na.locf() for details.
This is the xts method for the S3 generic na.locf(). The primary
difference to note is that after the NA fill action is carried out, the
default it to leave trailing or leading NA's in place. This is different
than zoo behavior.
x <- xts(1:10, Sys.Date()+1:10)
x[c(1,2,5,9,10)] <- NA
x
#> [,1]
#> 2025-11-01 NA
#> 2025-11-02 NA
#> 2025-11-03 3
#> 2025-11-04 4
#> 2025-11-05 NA
#> 2025-11-06 6
#> 2025-11-07 7
#> 2025-11-08 8
#> 2025-11-09 NA
#> 2025-11-10 NA
na.locf(x)
#> [,1]
#> 2025-11-01 NA
#> 2025-11-02 NA
#> 2025-11-03 3
#> 2025-11-04 4
#> 2025-11-05 4
#> 2025-11-06 6
#> 2025-11-07 7
#> 2025-11-08 8
#> 2025-11-09 8
#> 2025-11-10 8
na.locf(x, fromLast=TRUE)
#> [,1]
#> 2025-11-01 3
#> 2025-11-02 3
#> 2025-11-03 3
#> 2025-11-04 4
#> 2025-11-05 6
#> 2025-11-06 6
#> 2025-11-07 7
#> 2025-11-08 8
#> 2025-11-09 NA
#> 2025-11-10 NA
na.locf(x, na.rm=TRUE, fromLast=TRUE)
#> [,1]
#> 2025-11-01 3
#> 2025-11-02 3
#> 2025-11-03 3
#> 2025-11-04 4
#> 2025-11-05 6
#> 2025-11-06 6
#> 2025-11-07 7
#> 2025-11-08 8