christophsax / tempdisagg

Methods for Temporal Disaggregation and Interpolation of Time Series
http://cran.r-project.org/web/packages/tempdisagg
37 stars 5 forks source link

How to disaggregate daily series to hourly #39

Closed christophsax closed 4 years ago

christophsax commented 5 years ago
suppressMessages(library(dplyr))
library(tempdisagg)
library(tsbox)

discharge <- read.csv(text = "Date,A,C,B,D
                      2018-04-01,1290,735,5310,0
                      2018-04-02,1270,736,5290,0
                      2018-04-03,1220,1540,6860,0
                      2018-04-04,1200,3940,11400,0
                      2018-04-05,1290,5830,13000,0
                      2018-04-06,1660,6150,14500,0
                      2018-04-07,5030,6150,30300,0
                      2018-04-08,4490,4780,18600,0
                      2018-04-09,2620,3670,11000,843
                      2018-04-10,1870,3410,8260,1729
                      2018-04-11,1510,3190,7710,481
                      2018-04-12,1410,2700,7010,16
                      2018-04-13,1280,2350,6280,1
                      2018-04-14,1170,2060,6050,0
                      2018-04-15,1110,1770,5840,0",
                      header = TRUE, stringsAsFactors = FALSE)

### convert from daily discharge to volume
water_volume <-
  discharge %>%
  mutate(Date = as.POSIXct(Date)) %>%
  mutate_if(is.numeric, list(~ . * 86400))

tsbox works with long data.frames. In order to correctly detect the multiple series, use ts_long. However, tempdisagg only works on single series, so we use ts_pick to extract series ‘A’.

water_volume_d <- ts_pick(ts_xts(ts_long(water_volume)), "A")
#> [time]: 'Date' 
#> [time]: 'Date'
#> Loading required namespace: xts
#> Registered S3 method overwritten by 'xts':
#>   method     from
#>   as.zoo.xts zoo

### disaggregate from daily to hourly data

# method 'fast' is recommended for high frequency disaggregations, as they can
# become very slow.
test1 <- td(water_volume_d ~ 1, to = "hour", method = "fast")
water_volume_h <- predict(test1)

And the result:

ts_plot(water_volume_h, water_volume_d)

Created on 2019-09-15 by the reprex package (v0.3.0)