AnesG AnesG - 27 days ago 9
R Question

Reduce daily data in month and get the mean per month

I have a daily data of precipitation for 10 years like this
for the example only generate for 2 years

A <- seq(as.Date("2008/1/1"), as.Date("2009/12/31"), by = "day")
PP <- seq(1,731,1)
PPday <- data.frame(A,PP)


I manage to reduce de daily dates in month like this

Date <- as.POSIXct(strptime(A,"%Y-%m-%d"))
Datemonth <- seq.POSIXt(from=Date[1],to=Date[731],by="month")


But I cant find a way to get the mean per month of precipitation

PPMonth <- data.frame(Datemonth)

Answer Source

You can do this concisely and efficiently with data.table

library(data.table)
setDT(PPday)[, mean(PP), by = format(A, "%Y-%m")]
     format    V1
 1: 2008-01  16.0
 2: 2008-02  46.0
 3: 2008-03  76.0
 4: 2008-04 106.5
 5: 2008-05 137.0
 6: 2008-06 167.5
 7: 2008-07 198.0
 8: 2008-08 229.0
 9: 2008-09 259.5
10: 2008-10 290.0
11: 2008-11 320.5
12: 2008-12 351.0
13: 2009-01 382.0
14: 2009-02 411.5
15: 2009-03 441.0
16: 2009-04 471.5
17: 2009-05 502.0
18: 2009-06 532.5
19: 2009-07 563.0
20: 2009-08 594.0
21: 2009-09 624.5
22: 2009-10 655.0
23: 2009-11 685.5
24: 2009-12 716.0
     format    V1

EDIT: Thinking again - you're probably best off with base R:

  aggregate(PP ~ format(A, "%Y-%m"), data = PPday, mean)