You can use functions from the bizdays package in R to quickly add, subtract, and count the number of business days between two dates in R.
The following examples show how to use these functions in practice.
Example 1: Count Number of Business Days Between Two Dates in R
To count the number of business days between two dates in R, you must first use the create.calendar() function from the bizdays package to create a calendar that contains a list of business days:
library(bizdays)
#create business calendar
business_calendar calendar('my_calendar', weekdays = c('saturday','sunday'))
Note that the weekdays argument specifies which days of the week are not business days.
We can then use the bizdays() function to count the number of business days between two specific dates:
library(bizdays)
#calculate number of business days between two dates
bizdays(from = '2022-01-01', to = '2022-12-31', cal = business_calendar)
[1] 259
From the output we can see that there are 259 business days between 2022-01-01 and 2022-12-31.
Example 2: Add & Subtract Business Days from Date in R
Suppose we have the following data frame in R that contains information about the total sales made at some store on various dates:
#make this example reproducible
set.seed(1)
#create data frame
df frame(date = as.Date('2022-01-01') + 0:249,
sales = runif(n=250, min=1, max=30))
#view head of data frame
head(df)
date sales
1 2022-01-01 8.699751
2 2022-01-02 11.791593
3 2022-01-03 17.612748
4 2022-01-04 27.338026
5 2022-01-05 6.848776
6 2022-01-06 27.053301
We can use the offset() function from the bizdays package to add 10 business days to each date:
library(bizdays) #create business calendar business_calendar calendar('my_calendar', weekdays = c('saturday','sunday')) #add 10 business days to each date df$date 10, cal = business_calendar) #view updated head of data frame head(df) date sales 1 2022-01-14 8.699751 2 2022-01-14 11.791593 3 2022-01-17 17.612748 4 2022-01-18 27.338026 5 2022-01-19 6.848776 6 2022-01-20 27.053301
Notice that 10 business days have been added to each date.
To subtract business days, simply use a negative number in the offset() function.
For example, the following code shows how to subtract 10 business days from each date:
library(bizdays) #create business calendar business_calendar calendar('my_calendar', weekdays = c('saturday','sunday')) #subtract 10 business days to each date df$date 10, cal = business_calendar) #view updated head of data frame head(df) date sales 1 2021-12-20 8.699751 2 2021-12-20 11.791593 3 2021-12-20 17.612748 4 2021-12-21 27.338026 5 2021-12-22 6.848776 6 2021-12-23 27.053301
Notice that 10 business days have been subtracted from each date.
Note: You can find the complete documentation for the bizdays package here.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Convert Date to Numeric in R
How to Extract Month from Date in R
How to Add and Subtract Months from a Date in R