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

Time:10-09

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

CodePudding user response:

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)
}

CodePudding user response:

library(lubridate)

first_datex <- "2021-09-01-00"

gen_month <- function(first){
  
  end <- ymd_h(first_datex)   months(1) - hours(1)
  gen_date <- seq(ymd_h(first), end, by = "hours")
  data.frame(date(gen_date),hour(gen_date))
  
}

Then you can just run:

gen_month(first_datex)

You can check the function with:

identical(mydata, gen_month(first_datex)

Which yields TRUE

  • Related