Krishnang K Dalal
Krishnang K Dalal

Reputation: 2566

R: Group by data every N months

I have data from 2016-01-01 to 2017-07-30. I want to group_by data every three months and summarize. It's hard to show the entire data since it won't fit here. I generally use lubridate and dplyr for data manipulation but I am unable to figure out how to roll up data every three months. The pseudo code of what I am trying to accomplish is as below:

df$month <- month(as.Date(df$date))
df$year <- year(as.Date(df$date))
df %>% group_by(month + "3 Months", year) %>% summarise(n = sum(pageviews))

Can you please suggest me a simple way to do this? I know it's very simple using dplyr. Thanks a lot in advance.

Upvotes: 1

Views: 2272

Answers (1)

Brian
Brian

Reputation: 8295

df %>%
  mutate(dategroup = lubridate::floor_date(date, "2 months")) %>%
  group_by(dategroup) %>% ...

floor_date, ceiling_date, and round_date accept as arguments:

a character string specifying the time unit or a multiple of a unit to be rounded to. Valid base units are second, minute, hour, day, week, month, bimonth, quarter, halfyear, or year. Arbitrary unique English abbreviations as in period constructor are also supported. Rounding to multiple of units (except weeks) is supported from v1.6.0.

Upvotes: 4

Related Questions