Reduce daily data in month and get the mean per month [duplicate]

房东的猫 提交于 2020-01-24 20:48:31

问题


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)

回答1:


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)



回答2:


You can do this using dplyr + libridate:

library(dplyr)
library(lubridate)
PPday %>%
  mutate(byMonth = format(ymd(A), "%Y-%m")) %>%
  group_by(byMonth) %>%
  summarize(mean_PP = mean(PP)) %>%
  arrange(byMonth)

Result:

# A tibble: 24 × 2
   byMonth mean_PP
     <chr>   <dbl>
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
# ... with 14 more rows


来源:https://stackoverflow.com/questions/46374303/reduce-daily-data-in-month-and-get-the-mean-per-month

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!