0

I'm trying to calculate the difference in days between two dates, excluding weekends.

My Data looks like this:

    > head(order_time_dataset)
order_id order_DATE dispatch_DATE retailer_id
1:   699251 2016-01-26    2016-01-27           4
2:   693766 2016-01-08    2016-01-13           4
3:   692109 2016-01-03    2016-01-05           4
4:   701431 2016-02-02    2016-02-03        2365
5:   699878 2016-01-28    2016-01-29        2365
6:   699813 2016-01-28    2016-01-29        2365

And what I would like to get is an additional column with number of days, without counting weekends.

I have tried to follow this answer: Difference between two dates excluding weekends

and to adapt the original function to match the date format of my data:

getDuration <- function(d1, d2, fmt="%Y-%m-%d"){
    myDays <- seq.Date(to = as.Date(d2, format=fmt), from = as.Date(d1, format = fmt), by = 1)
    length(myDays[!is.weekend(myDays)])}

and then pass the two date columns of my data frame:

mapply(getDuration,order_time_dataset$dispatch_DATE,order_time_dataset$order_DATE)

but I'm getting this error:

Error in seq.int(0, to0 - from, by) : wrong sign in 'by' argument Called from: seq.Date(to = as.Date(d2, format = fmt), from = as.Date(d1, format = fmt), by = 1)

I think the error happens on seq.Date() and in fact if I try this:

seq.Date(to = as.Date(order_time_dataset$dispatch_DATE, format=fmt), from = as.Date(order_time_dataset$order_DATE, format = "%Y-%m-%d"), by = 1)

It gives me the following error:

Error in seq.Date(to = as.Date(order_time_dataset$dispatch_DATE, format = fmt), : 'from' must be of length 1

I tried to google about this error but I couldn't find anything that helped me understand what is causing this issue.

Could anyone please point me to the right direction?

Thanks a lot

Community
  • 1
  • 1
Giacomo
  • 1,796
  • 1
  • 24
  • 35
  • just change arguments `d1` and `d2` in your function `get_duration`. Or change order in `mapply(getDuration,order_time_dataset$order_DATE, order_time_dataset$dispatch_DATE)` – J_F Mar 07 '17 at 15:30
  • Thanks for the suggestion but unfortunately it doesn't seem to solve the problem. I still get the same error after I have changed the order. – Giacomo Mar 08 '17 at 21:36

0 Answers0