【问题标题】:Lubridate get date of certain day in a monthLubridate 获取一个月中某一天的日期
【发布时间】:2014-10-06 23:35:21
【问题描述】:

我想按月汇总我的日期。我想使用某个月的最后一个星期六作为该月的日期。 我可以通过以下方式获得一周内星期六的日期:

as.Date(paste(6, week(mdy(mydate)), year(mdy(mydate)), sep="-"), "%u-%W-%Y")

但是月份有不同的天数,所以我不能这样做:

as.Date(paste(6, month(mdy(mydate)), year(mdy(mydate)), sep="-"), "%U-%m-%Y")

这甚至都行不通,即使我只是想获得一个月的第 6 天的日期。

如何获取一个月的最后一个星期六的日期?所以给定一个日期09-15-2014 我会得到09-27-2014

【问题讨论】:

    标签: r lubridate


    【解决方案1】:

    1) zoo/cutzoo Quick Reference vignette 中出现这个函数,它给定一个"Date" 类变量x,如果是星期五,则返回相同的日期,否则返回下一个星期五:

    library(zoo)
    nextfri <- function(x) 7 * ceiling(as.numeric(x-5+4) / 7) + as.Date(5-4)
    

    将 5 替换为 6 将给出下一个星期六

    nextsat <- function(x) 7 * ceiling(as.numeric(x-6+4) / 7) + as.Date(6-4)
    

    现在如果 x 是输入并且属于 Date 类,则使用 cut 获取其月份的第一天,然后再次使用 cut 获取下个月的第一天,使用 nextsat 查找下一个星期六然后减去 7 得到输入日期月份的最后一个星期六。

    the.first <- as.Date(cut(x, "month"))
    next.month <- as.Date(cut(the.first + 32, "month")
    nextsat(next.month) - 7
    

    测试结束:

    library(zoo)
    x <- as.Date("2014-09-15")
    nextsat <- function(x) 7 * ceiling(as.numeric(x-6+4) / 7) + as.Date(6-4)
    the.first <- as.Date(cut(x, "month"))
    next.month <- as.Date(cut(the.first + 32, "month"))
    nextsat(next.month) - 7
    ## [1] "2014-09-27"
    

    这仅使用向量化函数,因此如果 x 是日期向量,它仍然可以工作。

    1a) zoo/as.yearmon.Date/as.Date.yearmon 我们可以通过使用 as.Date(as.yearmon(x), frac = 1) 是每月最后一天的日期来缩短它,其中 @987654334 @ 和 as.Date.yearmon 是 zoo 方法:

    library(zoo)
    x <- as.Date("2014-09-15")
    nextsat <- function(x) 7 * ceiling(as.numeric(x-6+4) / 7) + as.Date(6-4)
    nextsat(as.Date(as.yearmon(x), frac = 1) + 1) - 7
    ## [1] "2014-09-27"
    

    这也是矢量化的。

    2) zoo/lubridate 上面没有使用 lubridate 但我们可以修改 (1) 以像这样使用 lubridate:

    library(zoo)
    library(lubridate)
    nextsat <- function(x) 7 * ceiling(as.numeric(x-6+4) / 7) + as.Date(6-4)
    x <- as.Date("2014-09-15")
    xx <- x
    day(xx) <- 1
    month(xx) <- month(xx) + 1
    nextsat(xx) - 7
    ## [1] "2014-09-27"
    

    这也是矢量化的。

    【讨论】:

      【解决方案2】:

      使用标准 R 日期函数:

      x <- as.Date(c("09-15-2014","09-15-2014"),format="%m-%d-%Y")
      
      lastsat <- function(x,day) {
       bits <- sapply(x, function(i) {
        res <- seq.Date(as.Date(format(i,"%Y-%m-01")),length=2,by="1 month")[2] - (1:7)
        res[format(res, "%u") == as.character(day)]
       })
       as.Date(bits, origin="1970-01-01")
      }
      
      lastsat(x,6)
      #[1] "2014-09-27" "2014-09-27"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-28
        • 2021-10-26
        • 1970-01-01
        • 1970-01-01
        • 2011-03-31
        • 2016-01-22
        • 2023-04-02
        • 1970-01-01
        相关资源
        最近更新 更多