填补XTS中日期之间的空白

时间:2019-03-23 01:05:02

标签: r time-series xts

所以我有一个非常基本的问题。假设我们在一个时间序列对象中有一些日期间隔,我想用一个任意值来填充这些间隔。例如,假设我们有:

i <- c(seq.Date(from = as.Date("2015-01-01", format = "%Y-%m-%d"), to = as.Date("2016-01-01", format = "%Y-%m-%d"), by = "month"),
       seq.Date(from = as.Date("2017-01-01", format = "%Y-%m-%d"), to = as.Date("2018-01-01", format = "%Y-%m-%d"),by = "month"))

ts <- xts(rep(0,length(i)), order.by = i)

            [,1]
2015-01-01    0
2015-02-01    0
2015-03-01    0
2015-04-01    0
2015-05-01    0
2015-06-01    0
2015-07-01    0
2015-08-01    0
2015-09-01    0
2015-10-01    0
2015-11-01    0
2015-12-01    0
2016-01-01    0
2017-01-01    0
2017-02-01    0
2017-03-01    0
2017-04-01    0
2017-05-01    0
2017-06-01    0
2017-07-01    0
2017-08-01    0
2017-09-01    0
2017-10-01    0
2017-11-01    0
2017-12-01    0
2018-01-01    0

我希望实现的是在两个任意日期(即tsstart.date之间的所有月份的时间序列end.date上填充1。有什么建议吗?

我的尝试

  if(index(ts)[1] > start.date){
    len.aux <- length(seq(from = start.date, to = index(ts)[1] %m-% months(1), by = "month"))
    ts <- c(xts(rep(1, len.aux), order.by = seq.Date(from = start.date, to = index(ts)[1] %m-% months(1), by = "month")), ts)
  } 
  if(index(ts)[length(ts)] < end.date){
    len.aux <- length(seq(from = index(ts)[length(ts)] %m+% months(1), to = end.date, by = "month"))
    ts <- c(ts, xts(rep(1, len.aux), order.by = seq.Date(from = index(ts)[length(ts)] %m+% months(1), to = end.date, by = "month")))
  } 

但是,这只能填补系列“尾部”的空白,而不能填补两者之间的空白。

感谢您的帮助!

请注意,这只是我的问题的一个基本工作示例

1 个答案:

答案 0 :(得分:0)

您可以使用tsibble软件包:

library(tsibble)
i <- c(seq.Date(from = as.Date("2015-01-01", format = "%Y-%m-%d"), to = as.Date("2016-01-01", format = "%Y-%m-%d"), by = "month"),
       seq.Date(from = as.Date("2017-01-01", format = "%Y-%m-%d"), to = as.Date("2018-01-01", format = "%Y-%m-%d"),by = "month"))

tsibble(datetime = yearmonth(i), 
        value    = 0, index = datetime) %>% 
  fill_gaps(value = 1) %>% 
  View()

yearmonth函数将确保索引为每月(默认为每天)。函数fill_gaps将包含缺失的月份,并将value列中的缺失值设置为1(默认为NA)。