Fill NA in a time series only to a limited number

前端 未结 5 1007
滥情空心
滥情空心 2020-12-01 17:08

Is there a way we can fill NAs in a zoo or xts object with limited number of NAs forward. In other words like fill

5条回答
  •  半阙折子戏
    2020-12-01 17:50

    From playing around in data.table comes this hacky solution:

    np1 <- 3 + 1
    dt[, 
       x_filled := x[c(rep(1, min(np1, .N)), rep(NA, max(0, .N - np1)))],
       by = cumsum(!is.na(x))]
    # Or slightly simplified:
    dt[, 
       x_filled := ifelse(rowid(x) < 4, x[1], x[NA]),
       by = cumsum(!is.na(x))]
    
    > dt
              date  x x_filled
     1: 2019-02-14  1        1
     2: 2019-02-15 NA        1
     3: 2019-02-16 NA        1
     4: 2019-02-17 NA        1
     5: 2019-02-18  5        5
     6: 2019-02-19 NA        5
     7: 2019-02-20 NA        5
     8: 2019-02-21 NA        5
     9: 2019-02-22 NA       NA
    10: 2019-02-23 NA       NA
    11: 2019-02-24 11       11
    12: 2019-02-25 12       12
    13: 2019-02-26 NA       12
    14: 2019-02-27 NA       12
    15: 2019-02-28 NA       12
    16: 2019-03-01 NA       NA
    17: 2019-03-02 NA       NA
    18: 2019-03-03 NA       NA
    19: 2019-03-04 19       19
    20: 2019-03-05 20       20
    

    We build on the fact that subsetting vectors with NA returns NA.

    Data/Packages

    library(zoo)
    library(data.table)
    x <- zoo(1:20, Sys.Date() + 1:20)
    x[c(2:4, 6:10, 13:18)] <- NA
    dt <- data.table(date = index(x), x = as.integer(x))
    

提交回复
热议问题