How Can I us maxgap with na.fill on an zoo or xts?

Viewed 190

I would like to fill NAs with 0 in an xts with a maxgap of 3.

library(xts)

# make sample xts with gaps
x <- zoo(1:20, Sys.Date() + 1:20) 
x[2:4] <- NA # Short run of NA's 
x[10:16] <- NA # Long run of NA's 

#This is what I want to do, but it does not work
na.fill(x, 0, maxgap=3)

The maxgap argument is ignored and all NAs are filled with 0, I was hoping it would work like na.approx

Clarification to address @RLave 's question, I want to replace every series of NAs of length 3 or less. Series of NAs of length 4 or more should remain unmodified. Desired behavior should be the same as na.approx

3 Answers

There is an undocumented and unexported .fill_short_gaps in zoo that is used like this:

zoo:::.fill_short_gaps(x, fill = numeric(length(x)), maxgap = 3)

giving:

2019-01-17 2019-01-18 2019-01-19 2019-01-20 2019-01-21 2019-01-22 2019-01-23 
         1          0          0          0          5          6          7 
2019-01-24 2019-01-25 2019-01-26 2019-01-27 2019-01-28 2019-01-29 2019-01-30 
         8          9         NA         NA         NA         NA         NA 
2019-01-31 2019-02-01 2019-02-02 2019-02-03 2019-02-04 2019-02-05 
        NA         NA         17         18         19         20 

I'm not terribly familiar with zoo, so can't say whether it provides a function or argument will do this for you out of the box. That said, taking advantage of the ix argument to na.fill, you could write a simple wrapper function that provides the functionality you're wanting. Perhaps something like this:

f <- function(object, fill = 0, maxgap = Inf, ...) {
    rr <- rle(is.na(object))
    ii <- rep(rr$values == FALSE | rr$lengths > maxgap, rr$lengths)
    na.fill(object, fill, ix = ii)
}

f(x, 0, maxgap = 3)
## 2019-01-17 2019-01-18 2019-01-19 2019-01-20 2019-01-21 2019-01-22 2019-01-23 
##          1          0          0          0          5          6          7 
## 2019-01-24 2019-01-25 2019-01-26 2019-01-27 2019-01-28 2019-01-29 2019-01-30 
##          8          9         NA         NA         NA         NA         NA 
## 2019-01-31 2019-02-01 2019-02-02 2019-02-03 2019-02-04 2019-02-05 
##         NA         NA         17         18         19         20 

There is a quite easy method to do this with the imputeTS package:

library("imputeTS")
na_replace(x, fill = 0 , maxgap = 3)

This works with xts time series objects as input x, as well as with zoo series, vectors or normal time series.

Related