如何使用R查找当月的最后一个工作日(例如,星期三)?在下面的代码中,我计算月份,月份日期,月份周和工作日。 2014年1月有5个星期三,但2014年2月只有4个星期三,因此我不能使用max(月中的某个星期)作为过滤器。尽管我更喜欢使用基本的R函数,但是我们还是有任何帮助。
start "" "%site%"
答案 0 :(得分:6)
我认为这就是你所追求的:
DF$last_weekday_o_month <- ave(
weekdays(DF$DATE),
months(DF$DATE),
FUN = function(x) tail(x[ !(x %in% c("Saturday","Sunday")) ], 1)
)
查找上一个工作日的特定日期....
DF$last_weekdaydate_o_month <- ave(
DF$DATE,
months(DF$DATE),
FUN = function(x) tail(x[ !(weekdays(x) %in% c("Saturday","Sunday")) ], 1)
)
结果看起来像......
DATE last_weekday_o_month last_weekdaydate_o_month
1 2014-01-01 Friday 2014-01-31
2 2014-01-02 Friday 2014-01-31
3 2014-01-03 Friday 2014-01-31
4 2014-01-04 Friday 2014-01-31
5 2014-01-05 Friday 2014-01-31
6 2014-01-06 Friday 2014-01-31
...
360 2014-12-26 Wednesday 2014-12-31
361 2014-12-27 Wednesday 2014-12-31
362 2014-12-28 Wednesday 2014-12-31
363 2014-12-29 Wednesday 2014-12-31
364 2014-12-30 Wednesday 2014-12-31
365 2014-12-31 Wednesday 2014-12-31
如果您首先执行此操作,当然可以将last_weekday_o_month
计算为weekdays(last_weekdaydate_o_month)
。
根据@RichardScriven的建议,有了几个包,这可以更优雅/可读地完成:
library(data.table)
setDT(DF)[,
last_weekdaydate_o_month := last(DATE[!chron::is.weekend(DATE)])
, by = month(DATE)]
给出了
DATE last_weekdaydate_o_month
1: 2014-01-01 2014-01-31
2: 2014-01-02 2014-01-31
3: 2014-01-03 2014-01-31
4: 2014-01-04 2014-01-31
5: 2014-01-05 2014-01-31
---
361: 2014-12-27 2014-12-31
362: 2014-12-28 2014-12-31
363: 2014-12-29 2014-12-31
364: 2014-12-30 2014-12-31
365: 2014-12-31 2014-12-31
答案 1 :(得分:6)
以下是使用dplyr
的方法。基本上你按月分组,过滤掉周末&#39;天,并返回最后一天(即最大)的工作日。
library(dplyr)
DF <- data.frame(DATE = seq(as.Date("2014-01-01"), as.Date("2014-12-31"), "day"))
DF %>%
mutate(month = months(DATE), weekday = weekdays(DATE)) %>%
group_by(month) %>%
filter(!weekday %in% c("Saturday", "Sunday")) %>%
summarise(last_weekday = weekdays(max(DATE)))
Source: local data frame [12 x 2]
month last_weekday
1 April Wednesday
2 August Friday
3 December Wednesday
4 February Friday
5 January Friday
6 July Thursday
7 June Monday
8 March Monday
9 May Friday
10 November Friday
11 October Friday
12 September Tuesday
答案 2 :(得分:0)
library(lubridate)
x <- seq(as.Date("2007-12-31"), by="1 day", length.out=(Sys.Date() - as.Date("2007-12-31")))
library(plyr)
df <- data.frame(date=x, year=year(x), month=month(x))
df[,"weekday"] <- weekdays(df[,"date"])
df<- df[! df[,"weekday"] %in% c("Saturday", "Sunday"),]
df <- ddply(df, .(year, month), summarize, last=max(date))