Site icon Roel Peters

Counting, adding or subtracting business days in R

Calculating the number of days between two dates in R is as simple as using + or -. However, if you only want to count the business days (e.g. in a B2B context), you’ll have to be a little more creative. Let’s just do that.

Count business days in R

There are some very creative ways to count business days, but the most convenient one is definitely by using the bizdays R package.

Calculating the number of business days can be done using the (identically named) bizdays function. It takes only three arguments that you’ll need to achieve your goals: (1) the start date, (2) the end data and (3) a calendar object.

A calendar object can created using the create.calendar function. In this object you pass arguments that define which days are business days and which aren’t:

By using the create.calendar function and the bizdays function, it’s fairly easy to count business days between two dates.

library(bizdays)
business_calendar <- create.calendar('my_calendar', weekdays = c('saturday','sunday'))

# data.table way
df[,n_days := bizdays(start_date, end_date, cal = business_calendar)]

# dplyr way
df %>% 
	mutate(n_days = bizdays(start_date, end_date, cal = business_calendar))

Add or subtract business days in R

In the next example, I do not want to count the number of days between two dates. I want to add or subtract some business days from a specific date. Using the bizdays library, that’s once again very easy. It contains an offset() function to add or subtract business days from a specific date. Here, too, you need to specify the calendar object you’d like to use.

A good tip is to specify the library with the function, because offset is a fairly used function name in other libraries.

library(bizdays)
business_calendar <- create.calendar('my_calendar', weekdays = c('saturday','sunday'))

# data.table way
df[,added_10_biz_days := bizdays::offset(my_date, 10, cal = business_calendar)] # add
df[,added_10_biz_days := bizdays::offset(my_date, -10, cal = business_calendar)] # subtract

# dplyr way
df %>% 
	mutate(added_10_biz_days = bizdays::offset(my_date, 10, cal = business_calendar)) # add
	mutate(added_10_biz_days = bizdays::offset(my_date, 10, cal = business_calendar)) # subtract

Great success!

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Exit mobile version