Reputation: 494
I have monthly data over 2 years and 5 month. I want to have lead lagged values for next 7 months (future) starting from June 2017 till Dec 2017 ...
## DataSet
nr_serie_titles_live
2015-01-01 165
2015-02-01 170
2015-03-01 178
2015-04-01 188
2015-05-01 188
2015-06-01 194
2015-07-01 207
2015-08-01 216
2015-09-01 222
2015-10-01 226
2015-11-01 234
2015-12-01 237
2016-01-01 236
2016-02-01 245
2016-03-01 262
2016-04-01 266
2016-05-01 272
2016-06-01 275
2016-07-01 279
2016-08-01 281
2016-09-01 291
2016-10-01 304
2016-11-01 314
2016-12-01 324
2017-01-01 315
2017-02-01 324
2017-03-01 335
2017-04-01 352
2017-05-01 365
and I want values for coming 7 months
## values needed for 7 months
nr_serie_titles_live
01-06-2017 -
01-07-2017 -
01-08-2017 -
01-09-2017 -
01-10-2017 -
01-11-2017 -
01-12-2017 -
I tried "xts" package.
head(lag(date , 12), n = 7)
but I I don't understand. How I can get value for each month. So I should end up with 36 month of data with 29 month of original values and 7 months for future lagged values.
dput(xts_in_out_p_month)
structure(c(165, 170, 178, 188, 188, 194, 207, 216, 222, 226,
234, 237, 236, 245, 262, 266, 272, 275, 279, 281, 291, 304, 314,
324, 315, 324, 335, 352, 365), .Dim = c(29L, 1L), .Dimnames = list(
NULL, "nr_serie_titles_live"), index = structure(c(1420070400,
1422748800, 1425168000, 1427846400, 1430438400, 1433116800, 1435708800,
1438387200, 1441065600, 1443657600, 1446336000, 1448928000, 1451606400,
1454284800, 1456790400, 1459468800, 1462060800, 1464739200, 1467331200,
1470009600, 1472688000, 1475280000, 1477958400, 1480550400, 1483228800,
1485907200, 1488326400, 1491004800, 1493596800), tzone = "UTC",
tclass = "Date"), class = c("xts", "zoo"), .indexCLASS = "Date",
tclass = "Date", .indexTZ = "UTC", tzone = "UTC")
Your help would be much appreciated. Many thanks in advance !!!!
Upvotes: 1
Views: 582
Reputation: 3650
From your question I quite honestly did not get what is your desired output, but maybe you want something like this:
carrylastNForward <- function(x, n) {
p <- periodicity(x) # get end date date and frequency
xn <- length(x) # length of current time series
# create new time series time vector:
newtimes <- seq(p$end, by = p$label, length.out = n + 1)[-1]
new <- xts(x[(xn-n+1):length(x)], order.by = newtimes)
c(x, new) # combine old and new time series
}
results:
> carrylastNForward(x, 7) # x <- xts_in_out_p_month
nr_serie_titles_live
2015-01-01 165
2015-02-01 170
2015-03-01 178
2015-04-01 188
2015-05-01 188
2015-06-01 194
2015-07-01 207
2015-08-01 216
2015-09-01 222
2015-10-01 226
2015-11-01 234
2015-12-01 237
2016-01-01 236
2016-02-01 245
2016-03-01 262
2016-04-01 266
2016-05-01 272
2016-06-01 275
2016-07-01 279
2016-08-01 281
2016-09-01 291
2016-10-01 304
2016-11-01 314
2016-12-01 324
2017-01-01 315
2017-02-01 324
2017-03-01 335
2017-04-01 352
2017-05-01 365
2017-06-01 314
2017-07-01 324
2017-08-01 315
2017-09-01 324
2017-10-01 335
2017-11-01 352
2017-12-01 365
Upvotes: 1