【问题标题】:finding the previous Monday查找前一个星期一
【发布时间】:2016-01-16 02:05:50
【问题描述】:

我正在寻找一种方法来查找上一个日历周的星期一的日期对象。例如,今天是 2016 年 1 月 15 日;我需要构建一个返回“2016-01-04 UTC”的函数

【问题讨论】:

  • 听起来是个很酷的功能。你有什么?
  • PrevMon <- function(x){ x <- as.POSIXlt(x, format = "%m/%d/%Y") x$mday <- x$mday - ((x$wday - 1) %% 7) - 7 return(x) }
  • 谢谢大家! Chris 的解决方案效果很好。

标签: r lubridate


【解决方案1】:

该问题要求“上一个日历周的星期一”。我们在下面假设这意味着您想要输入日期或之前的星期一。

请注意,最好使用"Date" 类,因为不需要时间并且"Date" 类没有时区,因此它可以避免与"POSIXt" 类相关的潜在时区错误。

动物园小插图中有nextfri 函数zoo quickref vignette,我们可以将其用作类似函数的基础。我们进行这些更改 (1) ceiling 被替换为 floor,(2) 5(星期五)被替换为 1(星期一)和 (3) 我们添加 origin= 参数 to as.Date -- 如果 zoo 是加载提供了默认来源,因此可以选择省略 origin= 参数。

此函数仅使用基数 R 并且是矢量化的。它接受 "Date" 类向量并返回一个 "Date" 类向量,其中包含相应输入日期或之前的星期一的日期。

lastmon <- function(x) 7 * floor(as.numeric(x-1+4)/7) + as.Date(1-4, origin="1970-01-01")

例如,

 > lastmon(as.Date(c("2016-01-15", "2016-01-11")))
[1] "2016-01-11" "2016-01-11"

lastmon 函数也可以简化为:

lastmon2 <- function(x) x - as.numeric(x-1+4)%%7

注意:另请参阅herehereherehere 的 SO 答案,了解 nextfri 或其变体的更多用法。

【讨论】:

    【解决方案2】:

    还有一个lubridate 解决方案(from martin.R):

    library(lubridate)
    ceiling_date(your_date, "week", 1)
    

    同样,要查找上周一:

    floor_date(your_date, "week", 1)
    

    Documentation of the functions.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      相关资源
      最近更新 更多