我有一系列的到达和离开日期。我想知道这些日期是否与周末重叠。我可以编写一个自定义函数来遍历区间中的每一天,看看它们是否是周末。是否有更简单的方法可以更好地扩展?
我正在使用lubridate,但如果能让我的工作更轻松,我很乐意使用不同的日期包。
答案 0 :(得分:2)
这个base-R解决方案怎么样:
# make a set of sequences from beginning and ending dates and test with:
as.POSIXlt(x)$wday %in% c(0,6)
这将传递TRUE / FALSE的向量,您可以确定序列中的任何项目是否为TRUE:
max( as.POSIXlt(x)$wday %in% c(0,6) )
答案 1 :(得分:1)
a_date作为到达日期和d_date ansd出发日期,这样的事情可以起作用:
require(lubridate)
weekend_overlap <- ifelse(wday(a_date) %in% c(1, 7) ||
wday(d_date) %in% c(1, 7) ||
interval(a_date,d_date)/ddays(1) > 4,TRUE,FALSE)
答案 2 :(得分:0)
这是一个更通用的(矢量化)函数,用于检查间隔from
-to
是否包含某个工作日(1-7):
#' Check if a weekday is within an interval
#'
#' @param wday Day of week (integer 1-7)
#' @param from Date. Can be a vector.
#' @param to Date. Same length as `from` and must be greater than `from`.
#' @param week_start 1 = Monday. 7 = Sunday
#'
wday_in_interval = function(wday, from, to, week_start = 1) {
if (wday < 1 | weekday > 7)
stop("wday must be an integer from 1 to 7.")
if (week_start)
wday = 1 + (((wday - 2) + week_start ) %% 7) # Translate wday to week_start = 1 (ISO standard)
if (any(from > to, na.rm = TRUE))
stop("`from` must come before `to`")
# If the interval is greater than a week, it trivially contains any weekday
over_a_week = difftime(from, to, units = "days") >= 7
# Check if weekday is both smaller/greater than "from" and "to"
days_from = as.numeric(strftime(from, "%u"))
days_to = as.numeric(strftime(to, "%u"))
contains_weekday = ifelse(
strftime(from, "%V") == strftime(to, "%V"), # Dates are in the same week?
yes = wday >= days_from & wday <= days_to,
no = wday >= days_from | wday <= days_to #
)
return(over_a_week | contains_weekday)
}
找出时间间隔是否包含周末,只需检查该时间间隔是否不包含星期六或星期日:
library(dplyr)
tibble::tibble(
timestamp = seq(as.POSIXct("2020-09-03 0:00"), as.POSIXct("2020-09-8 12: 00"), length.out = 10),
overlaps_saturday = wday_in_interval(6, from = lag(timestamp), to = timestamp),
overlaps_sunday = wday_in_interval(7, from = lag(timestamp), to = timestamp),
overlaps_weekend = overlaps_saturday | overlaps_sunday
)
结果:
# A tibble: 10 x 4
timestamp overlaps_saturday overlaps_sunday overlaps_weekend
<dttm> <lgl> <lgl> <lgl>
1 2020-09-03 00:00:00 NA NA NA
2 2020-09-03 14:40:00 FALSE FALSE FALSE
3 2020-09-04 05:20:00 FALSE FALSE FALSE
4 2020-09-04 20:00:00 FALSE FALSE FALSE
5 2020-09-05 10:40:00 TRUE FALSE TRUE
6 2020-09-06 01:20:00 TRUE TRUE TRUE
7 2020-09-06 16:00:00 FALSE TRUE TRUE
8 2020-09-07 06:40:00 FALSE TRUE TRUE
9 2020-09-07 21:20:00 FALSE FALSE FALSE
10 2020-09-08 12:00:00 FALSE FALSE FALSE