A shorter solution is probably possible, but I find this very readable :)
The abbreviated month is in my locale (dutch)... it changes depending on your PC-settings.. or you can set it inline (?lubridate::month
)
library(tidyverse)
library(lubridate)
#create a vector of all dates within the given ranges
v <- apply( df, 1, function(x) {seq( as.Date(x[2], format = "%Y-%m-%d"), as.Date(x[3], format = "%Y-%m-%d"), by ="day" )}) %>%
unlist() %>%
as.Date( origin = "1970-01-01" )
#put the dates in a data.frame, use lubridate to extract year and month-data
df2 <- data.frame ( date = v ) %>%
mutate( Ano = lubridate::year( date ) ) %>%
mutate( Mes = lubridate::month( date, abbr = TRUE, label = TRUE ) ) %>%
group_by( Ano, Mes ) %>%
summarise( Value = n() ) %>%
select( Ano, Mes, Value)
# > df2
# # A tibble: 6 x 3
# # Groups: Ano [2]
# Ano Mes Value
# <dbl> <ord> <int>
# 1 2015 okt 2
# 2 2015 nov 33
# 3 2015 dec 55
# 4 2016 jan 33
# 5 2016 feb 29
# 6 2016 mrt 5