繁体   English   中英

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

[英]Calculating business days between two dataframe columns

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

试试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个工作日。 当我查看2017年8月25日至2017年9月6日之间的8个工作日时,这看起来很正确。

使用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,所以我们可以将所有非周末天数相加。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM