Bobolink47
Bobolink47

Reputation: 21

apply.monthly gives date of last observation in the month, not the last day of month

I have a time series (xts object) that is composed of a value for several days of a month over 65 years. Here are the head and tail of the time series:

1951-08-10  61.4030
1952-01-12  52.3773
1952-05-03 123.2899
1952-06-04 159.8922
1952-06-25 216.2244
1952-11-16 145.0869
....
2014-11-05  8.055283
2014-12-31 13.814598
2015-01-24 17.147218
2015-02-17 16.838870
2015-03-05 18.058845
2015-03-29 15.313688

There is no simple periodicity for the days within a month. The number of values ranges from 1 to 4 in any one month; some month are missing entirely. I want to make this into a monthly time series. When I run apply.monthly with FUN=mean on the xts object the result is a monthly time series with the DATE as the date of the last record for that month, not the date of the last day of the month, which is what I want.

I have run many other time series on daily data and I get the last day of the month when I use apply.monthly and I cannot figure out why this does not work the same. I have found examples (for example in the R Cookbook) that show nearly exactly this use and the output is the last day of the month. I want the last day of the month to match another time series I am comparing it with. I have tried using roll.apply with align=c("right"), but that gives the same result.

Is there a way to force apply.monthly to give the last day of the month, instead of the last date within a month in the output? Or is there something in my time series that is causing this output instead of what appears to be "standard" output of the last day of the month as the date?

Upvotes: 2

Views: 2438

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

apply.monthly always returns the last observation of each observed month, and never the last date of all months. It probably returns the last day of the month in the other situations because your data have an observation on the last day of the month.

But you don't need apply.monthly to do this in order to do what you want.

# sample data
x <-
  structure(c(8.055283, 13.814598, 17.147218, 16.83887, 18.058845, 15.313688),
    .Dim = c(6L, 1L), index = structure(c(1415145600, 1419984000, 1422057600,
    1424131200, 1425513600, 1427587200), tzone = "UTC", tclass = "Date"),
    class = c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date",
   .indexTZ = "UTC", tzone = "UTC")
m <- xts(1:5, seq(as.Date("2014-12-01"), by="month", length=5) - 1)
# merge your data with an 'empty' xts object with an end-of-month index
eom <- xts(,index(m))
mx <- apply.monthly(merge(x, eom), mean, na.rm=TRUE)
#                    x
# 2014-11-30  8.055283
# 2014-12-31 13.814598
# 2015-01-31 17.147218
# 2015-02-28 16.838870
# 2015-03-31 16.686267

Upvotes: 3

Related Questions