gpt4 book ai didi

r - 如何计算 networkdays 减去两个日期之间的假期

转载 作者:行者123 更新时间:2023-12-04 09:41:05 25 4
gpt4 key购买 nike

我正在尝试了解如何应用类似 NETWORKDAYS 的函数在 Excel 中。我花了一些时间搜索并找到了一些示例,但无法使 1 正常工作。

示例 1:

library(lubridate)
Date1 <- dmy("01/04/2017")
Date2 <- dmy("28/04/2017")
sum(!weekdays(seq(Date1, Date2, "days")) %in% c("Saturday", "Sunday"))

这工作正常,但需要删除假期

示例 2:

workdays = function(iniDate, endDate, holidays) {
theDates = seq(from=iniDate,to=endDate,by="day")
isHoliday = theDates %in% holidays
isWeekend = (as.POSIXlt(theDates)$wday) %in% (c(0,6))
return (sum(!isHoliday & !isWeekend))
}

这似乎是我最好的选择,但我不知道如何创建银行假日向量以应用于函数。

我如何使用这个函数,或者是否有更好的方法来计算 2 个日期之间的工作日(不包括节假日)?

最佳答案

我认为你很接近:如果有从 2017-04-012017-04-28 的天数向量,来自:

allDays <- seq.Date(from=as.Date("2017-04-01"), to=as.Date("2017-04-28"), by=1)

假期向量来自:

easter <- c(as.Date("2017-04-15"), as.Date("2017-04-16"), as.Date("2017-04-17"))

然后您可以使用 setdiff 删除假期功能:

nonHolidays <- as.Date(setdiff(allDays, easter ), origin="1970-01-01")

使用与您的第一个示例类似的方法,返回周末:

weekends <- nonHolidays[weekdays(nonHolidays) %in% c("Saturday", "Sunday")]

并且可以再次使用 setdiff 从非假期中删除周末:

nonHolidaysWeekends <- as.Date(setdiff(nonHolidays, weekends), origin="1970-01-01")

因此,您可以将其包装在返回 nonHolidaysWeekends 长度的函数中:

networkDays <- function(beginDate, endDate, holidayDates) {
# get all days between beginDate and endDate
allDays <- seq.Date(from=beginDate, to=endDate, by=1)
# use setdiff to remove holidayDates and convert back to date vector
nonHolidays <- as.Date(setdiff(allDays, holidayDates), origin="1970-01-01")
# find all weekends left in nonHolidays
weekends <- nonHolidays[weekdays(nonHolidays) %in% c("Saturday", "Sunday")]
# use setdiff again to remove the weekends from nonHolidays and convert back to date vector
nonHolidaysWeekends <- as.Date(setdiff(nonHolidays, weekends), origin="1970-01-01")
# return length of vector filtered for holidays and weekends
length(nonHolidaysWeekends)
}

d1 <- as.Date("2017-04-01")
d2 <- as.Date("2017-04-28")
# includes Easter Sunday
easter <- c(as.Date("2017-04-15"), as.Date("2017-04-16"), as.Date("2017-04-17"))
networkDays(d1, d2, easter)

有个类似的问题here如果有兴趣。

关于r - 如何计算 networkdays 减去两个日期之间的假期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47101895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com