Murali Murali - 3 months ago 27
R Question

Compute business days between two dates

New to R and learning lot and I love it.

My sales dataset has product, bpid, date. I would like to calculate the business difference between same bpid (just excluding Saturday & Sunday) .

If product or bpid changes (Or new bpid/product introduced), we need to skip the computations.

df <- data.frame(product=c('milk','milk','milk','milk','eggs','eggs','eggs','eggs'),
bpid=c(400,400,500,500,400,400,500,500),
date=c("2016-08-03","2016-08-10","2016-08-04","2016-08-10","2016-08-10","2016-08-16","2016-08-11","2016-08-15"));

df$date <- as.Date(df$date, format = "%Y-%m-%d");


My Desired result would be like below. Please help....

product bpid date compute-result
milk 400 2016-08-03 0
milk 400 2016-08-10 5
milk 500 2016-08-04 0
milk 500 2016-08-10 5
eggs 400 2016-08-10 0
eggs 400 2016-08-16 4
eggs 500 2016-08-11 0
eggs 500 2016-08-15 2

Answer

For example:

# install.packages("bizdays")
library(bizdays)
cal <-  Calendar(weekdays=c("saturday", "sunday"))
df$`compute-result` <- 0
idx <- seq(1, nrow(df),2)
df$`compute-result`[idx+1] <- bizdays(df$date[idx], df$date[idx+1], cal)
df
#   product bpid       date compute-result
# 1    milk  400 2016-08-03              0
# 2    milk  400 2016-08-10              5
# 3    milk  500 2016-08-04              0
# 4    milk  500 2016-08-10              4
# 5    eggs  400 2016-08-10              0
# 6    eggs  400 2016-08-16              4
# 7    eggs  500 2016-08-11              0
# 8    eggs  500 2016-08-15              2
Comments