确定R中两个日期之间的工作日 [英] Determine if a weekday is between two dates in R
本文介绍了确定R中两个日期之间的工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[更新]
在另一个线程,@Frank的答案解决了这个问题。这个问题与另一个问题重复。
In another thread, the answer from @Frank solves the problem. This question becomes duplicate of the other.
[问题]
我正在 R
中写一个函数来测试一个工作日是否在两个日期之间。这是我所拥有的,但我认为解决方案不是优雅的。有更多的数学方法吗?
I am writing a function in R
to test if a weekday is in between two dates. Here is what I have, but I think the solution is not elegant. Is there a more mathematical way to do it?
library(data.table) ## wday is a function in this package
isDayIn <- function(weekday, date1, date2) {
if (weekday<1 | weekday>7) stop("weekday must be an integer from 1 to 7.")
date1 <- as.Date(date1)
date2 <- as.Date(date2)
output <- weekday %in% unique(wday(seq.Date(date1, date2, by=1)))
return(output)
}
## 2015-08-02 is a Sunday and 2015-08-03 is a Monday
isDayIn(1, "2015-08-02", "2015-08-03")
> TRUE
isDayIn(7, "2015-08-02", "2015-08-03")
> FALSE
注意:函数 wday
开始星期日和星期六结束,所以星期日将被映射到整数1,星期六将被映射到整数7。
Note: the function wday
starts on Sunday and ends on Saturday, so Sunday will be mapped to integer 1 and Saturday will be mapped to integer 7.
推荐答案
另一个功能选项使用 base R
:
isDayIn <- function(weekday, date1, date2) {
if (weekday<1 | weekday>7) stop("weekday must be an integer from 1 to 7.")
weekday %in% strftime(seq(as.Date(date1), as.Date(date2), by="day"), format="%w")
}
isDayIn(1, "2015-08-02", "2015-08-03")
[1] TRUE
isDayIn(7, "2015-08-02", "2015-08-03")
[1] FALSE
这篇关于确定R中两个日期之间的工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文