R-计算两个数据帧列之间的工作日



我有一个包含两个posixct列的数据框架。我该如何计算这两个列之间的工作日数?

df <- data.frame(StartDate=as.POSIXct(c("2017-05-17 12:53:00","2017-08-31 21:16:00","2017-08-25 13:54:00","2017-09-06 15:47:00","2017-10-15 05:11:00"), format = "%Y-%m-%d %H:%M:%S"),
             EndDate=as.POSIXct(c("2017-06-09 11:57:00","2017-11-29 16:51:00","2017-09-06 15:13:00","2018-01-03 16:22:00","2017-11-17 11:51:00"), format = "%Y-%m-%d %H:%M:%S"))

使用 dplyr

df %>% 
  dplyr::rowwise() %>% 
  dplyr::mutate(wdays = sum(!weekdays(seq(StartDate, EndDate, by="day")) %in% c("Saturday", "Sunday")))
Source: local data frame [5 x 3]
Groups: <by row>
# A tibble: 5 x 3
  StartDate           EndDate             wdays
  <dttm>              <dttm>              <int>
1 2017-05-17 12:53:00 2017-06-09 11:57:00    17
2 2017-08-31 21:16:00 2017-11-29 16:51:00    64
3 2017-08-25 13:54:00 2017-09-06 15:13:00     9
4 2017-09-06 15:47:00 2018-01-03 16:22:00    86
5 2017-10-15 05:11:00 2017-11-17 11:51:00    25

这利用了可以轻松测序日期的事实,并且由于 TRUE等于一个,我们可以总结所有的非周末天。

尝试bizdays软件包:

library(bizdays) # Load the package
## Make a calendar that excludes Saturdays and Sundays
create.calendar("Workdays",weekdays = c("saturday", "sunday"))
## Calculate difference in days using the new Workdays calendar
df$bizdays <- bizdays(df$StartDate,df$EndDate,"Workdays")
df$bizdays
[1] 17 63  8 85 24

返回了您提供的开始日期和结束日期之间的17、63、8、85和24个工作日。当我检查8/25/2017和9/6/2017之间的8个工作日时,这看起来正确。

最新更新