Search code examples
rtime-seriesxts

Converting daily data to summed/averaged monthly data with a specific layout format


I've looked through similar past questions but have yet to find something specific to what I'm looking for.

I have daily data, that I would like to convert to average/sum monthly data. With the final product being a dataframe with months in the column and years in the rows Example.

I've managed to get the monthly average of my dataset using:

library(xts)
ts <- xts(data$tmax, as.Date(data$date, "%Y-%m-%d"))
ts_m = apply.monthly(ts, mean)

    data$Date   data$tmax
1   1951-01-01  3.22777778
2   1951-01-02  6.48888889
3   1951-01-03  10.52777778
4   1951-01-04  1.92777778
5   1951-01-05  1.30000000
6   1951-01-06  0.10000000
7   1951-01-07  -6.72777778
8   1951-01-08  -4.48888889
9   1951-01-09  -0.83888889
10  1951-02-01  -9.92777778
11  1951-02-02  -11.60000000
12  1951-02-03  -8.61111111
13  1951-02-04  -1.40000000
... ...        ...

The code above gives me an xts with the averages:

Y-M-D       Tmax_avg
1951-01-09  1.279630
1951-02-12  -3.548611

But I can't figure out out to convert the layout of the xts (or if I have to convert the xts) so that it looks like this (months running down, and years running across):

   1951   1952  1953
01 1.27   ...
02 -3.54  ...
...   
12 ...    ...

Thanks in advance!


Solution

  • We can extract the 'year' and the 'Date' and then use xtabs

    Year <- format(as.Date(index(tsm)), '%Y')
    Month <- format(as.Date(index(tsm)), '%m')
    df1 <- data.frame(Year, Month, tmax = tsm[,1])
    xtabs(tmax ~ Month + Year, df1)