Search code examples
rdplyrtidyrplyrlubridate

Generate date & hour based on month automatically using lubridate in R


I want to make a function to generate date & hour based on first date of the month. As sample i use september.

first_datex <- "2021-09-01"
gen_month <- function(first_datex){
# Need solution
}

The output that i want is like here:

library(lubridate)
gen_date <- seq(ymd_h("2021-09-01-00"), ymd_h("2021-09-30-23"), by = "hours")
hourx <- hour(gen_date)
datex <- date(gen_date)
mydata <- data.frame(datex, hourx)

head(mydata) #The Output
#       datex hourx
#1 2021-09-01     0
#2 2021-09-01     1
#3 2021-09-01     2
#4 2021-09-01     3
#5 2021-09-01     4
#6 2021-09-01     5

Solution

  • Here is an option -

    gen_month <- function(first_datex){
      first_datex <- as.Date(first_datex)
      last_datex <- seq(first_datex, length = 2, by = 'month')[2] - 1
      expand.grid(datex = seq(first_datex, last_datex, by = 'day'), 
                  hourx = 0:23)
    }
    
    gen_month("2021-09-01")
    

    Another option using lubridate::ceiling_date and tidyr::expand_grid.

    gen_month <- function(first_datex){
      first_datex <- as.Date(first_datex)
      last_datex <- lubridate::ceiling_date(first_datex, 'month') - 1
      tidyr::expand_grid(datex = seq(first_datex, last_datex, by = 'day'), 
                  hourx = 0:23)
    }