计算两个数据框列之间的工作日

时间:2018-02-14 22:10:09

标签: r bizdays

我有一个包含两个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"))

2 个答案:

答案 0 :(得分:2)

试用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个工作日时,这看起来是正确的。

答案 1 :(得分:1)

使用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等于1,我们可以总结所有非周末日。