As input I have a time series known at daily time points. We may refer to this time series as _x_
. The object _x_
is a time series, i.e. consisting of dates and measurements.
I would like to investigate the effect of keeping the time series constant in each month. In other words, I would like to have a new time series _y_
that still has a daily frequency but the observations in the months are kept constant equal to the first value in the month.
I have looked into this and tried to use the 'tempdisagg'
package, specifically the 'td'
function. However, this seems too complicated for my purpose and requires a formula as input. Furthermore supposing each month has 30 days will create a discrepancy between _x_
and _y_
, which is not desirable as the length of the time series is several years.
Is there a solution to enable this?
Creation of x (time series)
x <- ts(seq(1:62), frequency = 365, start = c(2017, as.numeric(format(as.Date("2017-12-01"), "%j"))) )
Creation of a dataframe (db) with the timeseries, the daily and monthly data
library(lubridate)
tms <- date_decimal(as.numeric(time(x)))
y_m<-as.character(substr(as.character(tms),1,7))
db<-as.data.frame(cbind(as.numeric(x),as.character(tms),y_m))
colnames(db)<-c("time_series","y_m_d","y_m")
Extraction of the first value for each month
db_first<-db[!duplicated(db$y_m),]
Creation of the final output
db_merge<-as.data.frame(merge(x=db,y=db_first,by="y_m",all=T))
db_final<-as.data.frame(cbind(as.character(db_merge$y_m),as.numeric(as.character(db_merge$time_series.y))))
colnames(db_final)<-c("y_m","time_series")
y_m time_series
1 2017-12 1
2 2017-12 1
3 2017-12 1
4 2017-12 1
5 2017-12 1
6 2017-12 1
7 2017-12 1
8 2017-12 1
9 2017-12 1
10 2017-12 1
11 2017-12 1
12 2017-12 1
13 2017-12 1
14 2017-12 1
15 2017-12 1
16 2017-12 1
17 2017-12 1
18 2017-12 1
19 2017-12 1
20 2017-12 1
21 2017-12 1
22 2017-12 1
23 2017-12 1
24 2017-12 1
25 2017-12 1
26 2017-12 1
27 2017-12 1
28 2017-12 1
29 2017-12 1
30 2017-12 1
31 2017-12 1
32 2018-01 32
33 2018-01 32
34 2018-01 32
35 2018-01 32
36 2018-01 32
37 2018-01 32
38 2018-01 32
39 2018-01 32
40 2018-01 32
41 2018-01 32
42 2018-01 32
43 2018-01 32
44 2018-01 32
45 2018-01 32
46 2018-01 32
47 2018-01 32
48 2018-01 32
49 2018-01 32
50 2018-01 32
51 2018-01 32
52 2018-01 32
53 2018-01 32
54 2018-01 32
55 2018-01 32
56 2018-01 32
57 2018-01 32
58 2018-01 32
59 2018-01 32
60 2018-01 32
61 2018-01 32
62 2018-01 32