How do I group my date variable into month/year in R?

The floor_date() function from the lubridate package does this nicely.

data %>% 
    group_by(month = lubridate::floor_date(date, "month")) %>%
    summarize(summary_variable = sum(value))

Thanks to Roman Cheplyaka https://ro-che.info/articles/2017-02-22-group_by_month_r

See more on how to use the function: https://lubridate.tidyverse.org/reference/round_date.html


Maybe you just add a column in your data like this:

Year <- format(as.Date(Entered_Date, "%d/%m/%Y"), "%Y")


Here is an example using dplyr. You simply use the corresponding date format string for month %m or year %Y in the format statement.

set.seed(123)
df <- data.frame(date = seq.Date(from =as.Date("01/01/1998", "%d/%m/%Y"), 
                                 to=as.Date("01/01/2000", "%d/%m/%Y"), by="day"),
                 value = sample(seq(5), 731, replace = TRUE))

head(df)
        date value
1 1998-01-01     2
2 1998-01-02     4
3 1998-01-03     3
4 1998-01-04     5
5 1998-01-05     5
6 1998-01-06     1

library(dplyr)

df %>%
mutate(month = format(date, "%m"), year = format(date, "%Y")) %>%
group_by(month, year) %>%
summarise(total = sum(value))

Source: local data frame [25 x 3]
Groups: month [?]

   month  year total
   (chr) (chr) (int)
1     01  1998   105
2     01  1999    91
3     01  2000     3
4     02  1998    74
5     02  1999    77
6     03  1998    96
7     03  1999    86
8     04  1998    91
9     04  1999    95
10    05  1998    93
..   ...   ...   ...

Just to add to @cdeterman answer, you can use lubridate along with dplyr to make this even easier:

df <- data.frame(date = seq.Date(from =as.Date("01/01/1998", "%d/%m/%Y"), 
                                 to=as.Date("01/01/2000", "%d/%m/%Y"), by="day"),
                 value = sample(seq(5), 731, replace = TRUE))

library(dplyr)
library(lubridate)

df %>%
mutate(month = month(date), year = year(date)) %>%
group_by(month, year) %>%
summarise(total = sum(value))

Tags:

Plot

R

Grouping