在计算工作日的日期差异时遇到问题,即在Excel中排除网络日期功能等周末。
这是我的数据。
e <- structure(list(date.pr = structure(c(15909, 15933, 16517, 15961, 15974, 15978), class = "Date"), date.po = structure(c(15909, 15933, 15954, 15961, 15974, 15978), class = "Date")), .Names = c("date.1", "date.2"), class = c("tbl_df", "data.frame"), row.names = c(NA, -6L))
找到此任务的“bizdays”包。哪个适合这个。
> bizdays(e$date.2,e$date.1)
[1] 0 0 563 0 0 0
但我的数据包含date.2在date.1之前的情况。
e2 <- structure(list(date.pr = structure(c(15909, 15933, 16517, 15961, 5974, 15978, 15978), class = "Date"), date.po = structure(c(15909, 15933, 15954, 15961, 15974, 15978, 15979), class = "Date")), .Names = c("date.1", "date.2"), class = c("tbl_df", "data.frame"), row.names = c(NA, -7L))
现在它出现以下错误:
> cal <- Calendar(holidaysANBIMA, weekdays=c("saturday","sunday"))
> bizdays(e2$date.2,e2$date.1,cal)
Error in bizdays.Date(e2$date.2, e2$date.1, cal) :
All from dates must be greater than all to dates.
我在考虑使用ifelse()逻辑,但它给了我同样的错误。
> ifelse(e2$date.2 < e2$date.1, NA, bizdays(e2$date.2,e2$date.1,cal))
Error in bizdays.Date(e2$date.2, e2$date.1, cal) :
All from dates must be greater than all to dates.
帮助表示赞赏。
答案 0 :(得分:1)
Nweekdays()
功能改编自@J。韩元。解决方案Calculate the number of weekdays between 2 dates in R
此修改后的功能考虑了正面或负面的日期差异, 而上述链接已接受正日期差异的解决方案。
library("dplyr")
e2 <- structure(list(date.pr = structure(c(16524, 16524, 16507, 16510, 16510, 16524, 16510, 5974), class = "Date"),
date.po = structure(c(16524, 16525, 16510, 16517, 16524, 16510, 16531, 15974), class = "Date")),
.Names = c("date.1", "date.2"), class = c("tbl_df", "data.frame"), row.names = c(NA, -8L))
Nweekdays <- Vectorize(
function(a, b)
{
ifelse(a < b,
return(sum(!weekdays(seq(a, b, "days")) %in% c("Saturday", "Sunday")) - 1),
return(sum(!weekdays(seq(b, a, "days")) %in% c("Saturday", "Sunday")) - 1))
})
> e2 %>%
mutate(wkd1 = format(date.1, "%A"),
wkd2 = format(date.2, "%A"),
ndays_with_wkends = ifelse((date.2 > date.1), (date.2 - date.1), (date.1 - date.2)),
ndays_no_wkends = Nweekdays(date.1, date.2))
Source: local data frame [8 x 6]
date.1 date.2 wkd1 wkd2 ndays_with_wkends ndays_no_wkends
(date) (date) (chr) (chr) (dbl) (dbl)
1 2015-03-30 2015-03-30 Monday Monday 0 0
2 2015-03-30 2015-03-31 Monday Tuesday 1 1
3 2015-03-13 2015-03-16 Friday Monday 3 1
4 2015-03-16 2015-03-23 Monday Monday 7 5
5 2015-03-16 2015-03-30 Monday Monday 14 10
6 2015-03-30 2015-03-16 Monday Monday 14 10
7 2015-03-16 2015-04-06 Monday Monday 21 15
8 1986-05-11 2013-09-26 Sunday Thursday 10000 7143
> e2 %>% mutate(ndays_no_wkends = Nweekdays(date.1, date.2))
Source: local data frame [8 x 3]
date.1 date.2 ndays_no_wkends
(date) (date) (dbl)
1 2015-03-30 2015-03-30 0
2 2015-03-30 2015-03-31 1
3 2015-03-13 2015-03-16 1
4 2015-03-16 2015-03-23 5
5 2015-03-16 2015-03-30 10
6 2015-03-30 2015-03-16 10
7 2015-03-16 2015-04-06 15
8 1986-05-11 2013-09-26 7143