Is there a function in R language that can be used to calculate the number of days excluding weekends and holidays? If you specify a 」start date 」 or 終了end date を for the argument, it is like calculating the number of days in that period.Holiday data is a prerequisite for manual preparation.
r
I don't know how you keep holiday data, but let's say it's a vector of the date and time string.
#For 2016, March 21st is a transfer holiday, but it is not included.
>holidays=c("2016/1/1", "2016/1/11", "2016/2/11", "2016/3/20", "2016/4/29",
"2016/5/3", "2016/5/4", "2016/5/5", "2016/7/18", "2016/8/11",
"2016/9/19", "2016/9/22", "2016/10/10", "2016/11/3", "2016/11/23",
"2016/12/23")
# Create a daily sequence from January 1, 2016 to October 23, 2016
>s=seq.Date(as.Date("2016/1/1"), as.Date("2016/10/23"), by="day")
# format(s, "%u") returns the day of the week as a number.Monday is one and Sunday is seven.
>length(s[format(s, "%u")<6&!format(s, "%Y/%-m/%-d")% in %holidays])
[1] 199
The timeDate
package has a function isWeekday()
that identifies weekdays and weekends, and I also have G7 holiday data including Japan... but I noticed that there was a omission after posting, so it's better not to use it.Instead, the jholiday()
function in the Nippon
package gets holiday data.
library(timeDate);library(Nippon)
## We are using the code metropolis.
days=seq.Date(as.Date("2016/1/1"), as.Date("2016/10/23"), by="day")
## Store 2016 holiday information
hol2016<-jholiday (2016)
## discrimination
weekday<-days[isWeekday(days)]#Exclude weekends first
heijitu<-weekday[!weekday%in%hol2016] #Next Exclude Holidays
length(heijitsu)#Check how many days are available
# [1] 198#metropolis deviation is due to transfer holiday on March 21st
For 2000 and beyond, we first used Vectorize()
for jholiday
, but because of this, as.numeric()
, we have as.Date()
returned to Date
.
heijitu.f<-function(start,end){
hol2000_2016<-as.Date(unlist(Vectorize(Nippon::jholiday, "year") (2000:2016))), origin="1970-1-1")
days<-seq.Date(as.Date(start), as.Date(end), by="day")
result<-length(days[timeDate::isWeekday(days)&!(days%in%hol2000_2016)])
return(result)
}
heijitu.f ("January 1, 2016, October 23, 2016")
# [1] 198
© 2024 OneMinuteCode. All rights reserved.