How to group by a custom date (month, day, year) range and create seasons across the time group and get summary?
This first identifies the day 2 months prior, which shifts everything into the year and section of the year it's season begins in. Then it defines an ordered factor with the name of the season in order starting from the spring. count(x, wt = y, name = "name")
is a shortcut for group_by(x) %>% summarize(name = sum(y))
so it works here for summing the climate numbers by year & season.
library(lubridate)
df %>%
mutate(date_2mo_ago = date %m-% months(2),
season_num = quarter(date_2mo_ago),
season = c("spring", "summer", "fall", "winter")[season_num] %>%
forcats::fct_reorder(season_num),
year = year(date_2mo_ago)) %>%
count(year, season, wt = climate, name = "climate")
Result
year season climate
1 1979 winter 2921
2 1980 spring 4744
3 1980 summer 4687
4 1980 fall 4392
5 1980 winter 4199
6 1981 spring 4456
7 1981 summer 4420
8 1981 fall 4330
9 1981 winter 4552
10 1982 spring 4870
11 1982 summer 4995
12 1982 fall 4622
13 1982 winter 1536