xts method replace NA with most recent non-NA
Usage
# S3 method for class 'xts'
na.locf(object, na.rm = FALSE, fromLast = FALSE, maxgap = Inf, ...)Arguments
- object
An xts object.
- na.rm
Logical indicating whether leading/trailing
NAshould be removed. The default isFALSEunlike the zoo method.- fromLast
Logical indicating whether observations should be carried backward rather than forward. Default is
FALSE.- maxgap
Consecutive runs of observations more than 'maxgap' will remain
NA. Seena.locf()for details.- ...
Unused.
Value
An object where each NA in object is replaced by the most recent
non-NA prior to it. See na.locf() for details.
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.
Examples
x <- xts(1:10, Sys.Date()+1:10)
x[c(1,2,5,9,10)] <- NA
x
#> [,1]
#> 2026-03-06 NA
#> 2026-03-07 NA
#> 2026-03-08 3
#> 2026-03-09 4
#> 2026-03-10 NA
#> 2026-03-11 6
#> 2026-03-12 7
#> 2026-03-13 8
#> 2026-03-14 NA
#> 2026-03-15 NA
na.locf(x)
#> [,1]
#> 2026-03-06 NA
#> 2026-03-07 NA
#> 2026-03-08 3
#> 2026-03-09 4
#> 2026-03-10 4
#> 2026-03-11 6
#> 2026-03-12 7
#> 2026-03-13 8
#> 2026-03-14 8
#> 2026-03-15 8
na.locf(x, fromLast=TRUE)
#> [,1]
#> 2026-03-06 3
#> 2026-03-07 3
#> 2026-03-08 3
#> 2026-03-09 4
#> 2026-03-10 6
#> 2026-03-11 6
#> 2026-03-12 7
#> 2026-03-13 8
#> 2026-03-14 NA
#> 2026-03-15 NA
na.locf(x, na.rm=TRUE, fromLast=TRUE)
#> [,1]
#> 2026-03-06 3
#> 2026-03-07 3
#> 2026-03-08 3
#> 2026-03-09 4
#> 2026-03-10 6
#> 2026-03-11 6
#> 2026-03-12 7
#> 2026-03-13 8