2014-10-06 182 views
2

我想在月度级别上汇总我的日期。我想用一个月的最后一个星期六作为那个月的日期。 我可以通过执行获得周六的日期在一周:Lubridate获取某月某天的日期

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

这甚至不工作,即使我只是想要得到一个月的第六天的日期。

我怎样才能得到一个月的最后一个星期六的日期?所以给定一个日期09-15-2014我会得到09-27-2014

回答

5

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.Dateas.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" 

这也向量化。

4

使用标准的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"