如何确定周末并从我的R时差中自动减去它

时间:2018-07-30 13:55:37

标签: r difftime

我正在编写一个代码,该代码使用两个时间戳记向量为我提供特定进程所需的时间(简称difftime)。

但是在周末,时间应该停止了。因此,如果某个产品在星期五进货而在星期二出门,则我必须减去周末时间。 因此,我需要一种可能性来确定产品处理时间何时经过一个周末,该周末会自动从时差中减去。

这些产品的识别比减法更多的是问题。

2 个答案:

答案 0 :(得分:3)

使用is.weekend包中的chron

days<-seq.Date(as.Date("01-01-2017",format= "%d-%m-%Y"),as.Date("01-04-2017",format= "%d-%m-%Y"),by = "days")   
library(chron)  
  days[is.weekend(days)]
  [1] "2017-01-01" "2017-01-07" "2017-01-08" "2017-01-14" "2017-01-15" "2017-01-21" "2017-01-22"
  [8] "2017-01-28" "2017-01-29" "2017-02-04" "2017-02-05" "2017-02-11" "2017-02-12" "2017-02-18"
 [15] "2017-02-19" "2017-02-25" "2017-02-26" "2017-03-04" "2017-03-05" "2017-03-11" "2017-03-12"
 [22] "2017-03-18" "2017-03-19" "2017-03-25" "2017-03-26" "2017-04-01"

  weekdays.Date(days[is.weekend(days)])
  [1] "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday"
  [9] "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday"
 [17] "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday" "Sunday"   "Saturday"
 [25] "Sunday"   "Saturday"

答案 1 :(得分:0)

函数weekdays在这里可能会有所帮助:

weekdays(as.Date("2018-07-30"))
# [1] "monday"

因此,如果您传递日期矢量对象,则可以设置周六和周日。

例如:

which(weekdays(as.Date(c("2018-07-30", "2018-07-29", "2018-07-28", "2018-07-27"))) %in% c("saturday", "sunday"))
[1] 2 3