将日数据转换为具有特定布局格式的 summed/averaged 月数据

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

我查看了过去类似的问题,但尚未找到与我正在寻找的内容相关的内容。

我有每日数据,我想将其转换为 average/sum 每月数据。最终产品是一个数据框,列中有月份,行中有年份 Example.

我使用以下方法获得了我的数据集的月平均值:

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
... ...        ...

上面的代码给出了一个 xts 的平均值:

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

但我不知道如何转换 xts 的布局(或者如果我必须转换 xts),使其看起来像这样(几个月 运行 和几年 运行横跨):

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

提前致谢!

我们可以提取 'year' 和 'Date' 然后使用 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)