我正在尝试计算两个日期之间的天数差异,不包括周末。
我的数据如下:
> 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
我想要的是一个额外的列,包含天数,不计算周末。
我试图按照这个答案:Difference between two dates excluding weekends
并调整原始函数以匹配我的数据的日期格式:
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)])}
然后传递我的数据框的两个日期列:
mapply(getDuration,order_time_dataset$dispatch_DATE,order_time_dataset$order_DATE)
但是我收到了这个错误:
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)
我认为错误发生在seq.Date()上,实际上如果我尝试这个:
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)
它给了我以下错误:
Error in seq.Date(to = as.Date(order_time_dataset$dispatch_DATE, format = fmt), :
'from' must be of length 1
我试图谷歌关于此错误,但我找不到任何有助于我了解导致此问题的原因。
有谁能请我指出正确的方向?
非常感谢