1)动物园/切断在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
,在拿到第一个月它的n再次使用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)动物园/ as.yearmon.Date/as.Date.yearmon我们可以用事实as.Date(as.yearmon(x), frac = 1)
就是as.yearmon.Date
和as.Date.yearmon
是动物园方法月份的最后一天的日期缩短这个:
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)动物园/ 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"
这也向量化。