【问题标题】:Generate date & hour based on month automatically using lubridate in R使用 R 中的 lubridate 根据月份自动生成日期和小时
【发布时间】:2021-11-28 20:47:47
【问题描述】:

我想创建一个函数来根据当月的第一个日期生成日期和小时。作为示例,我使用 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

【问题讨论】:

    标签: r dplyr tidyr plyr lubridate


    【解决方案1】:
    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

    【讨论】:

    • 先生,我们可以只使用 first_datex 而不使用 last_datex 吗?因为每个月都会使用该解决方案,而且我们知道每个月都有不同的日子。
    • @Faryan 当然!我更新了解决方案
    【解决方案2】:

    这是一个选项-

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 2021-10-08
      • 2012-01-08
      相关资源
      最近更新 更多