使用 R 中的 lubridate 根据月份自动生成日期和小时

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

我想制作一个函数,根据每月的第一天生成日期和时间。作为示例,我使用 9 月。

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

我想要的输出如下:

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

那么你可以 运行:

gen_month(first_datex)

您可以通过以下方式检查函数:

identical(mydata, gen_month(first_datex)

产生 TRUE

这里有一个选项-

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

使用 lubridate::ceiling_datetidyr::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)
}