首页 > 解决方案 > 将季度数据分解为 R 中的每日数据保持值?

问题描述

如何轻松地将季度数据分解为每日数据?在这种情况下,我使用了 10 年的美国 GDP 数据,这些数据具有季度观察值,并且我想将数据框扩展到每日级别,每天将 GDP 值延续到下一次观察。

代表表:

structure(list(thedate = structure(c(14426, 14518, 14610, 14700, 
14791, 14883, 14975, 15065, 15156, 15248, 15340, 15431, 15522, 
15614, 15706, 15796, 15887, 15979, 16071, 16161, 16252, 16344, 
16436, 16526, 16617, 16709, 16801, 16892, 16983, 17075, 17167, 
17257, 17348, 17440, 17532, 17622, 17713, 17805, 17897, 17987
), class = "Date"), gdp = c(1.5, 4.5, 1.5, 3.7, 3, 2, -1, 2.9, 
-0.1, 4.7, 3.2, 1.7, 0.5, 0.5, 3.6, 0.5, 3.2, 3.2, -1.1, 5.5, 
5, 2.3, 3.2, 3, 1.3, 0.1, 2, 1.9, 2.2, 2, 2.3, 2.2, 3.2, 3.5, 
2.5, 3.5, 2.9, 1.1, 3.1, 2.1)), class = "data.frame", row.names = c(NA, 
-40L))

我们在上面看到:

2009-07-01 | 1.5
2009-10-01 | 4.5

预期的输出如下所示:

2009-07-01 | 1.5
2009-07-02 | 1.5
2009-07-03 | 1.5
etc.
2009-10-01 | 4.5
2009-10-02 | 4.5
2009-10-03 | 4.5

标签: rdplyrlubridate

解决方案


这是一个 tidyr 和 zoo 包答案,它在插入带有 NA 的日期序列后使用“最后一次观察结转”:

library(tidyverse)
library(zoo)

data %>%
  complete(thedate = seq.Date(min(thedate), max(thedate), by="day")) %>%
  do(na.locf(.))

编辑:感谢 Shree 提醒 tidyr::fill 将消除对动物园的需求:

library(tidyverse)

data %>%
  complete(thedate = seq.Date(min(thedate), max(thedate), by="day")) %>%
  fill(gdp)

推荐阅读