1) zoo/cut 在zoo 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"
这也是矢量化的。