这是基于 tidyverse 和 lubridate 的可能解决方案。
首先,包含已预订的约会的小标题。一开始是空的。
library(tidyverse)
library(lubridate)
bookedAppointments <- tibble(
AppointmentDate=structure(NA_real_, class="Date"),
ParticipantID=numeric()
)
bookedAppointments
# A tibble: 0 x 2
# … with 2 variables: AppointmentDate <date>, ParticipantID <dbl>
现在,一个函数可以找到约会可用的最后可能日期之前的日期。
findAvailableSlots <- function(lastDate) {
bookedSlots <- bookedAppointments %>%
filter(AppointmentDate %within% interval(lastDate - days(14), lastDate)) %>%
group_by(AppointmentDate) %>%
summarise(BookedSlots=n())
availableSlots <- tibble(
AppointmentDate=lastDate - days(0:13),
MaximumSlots=8
) %>%
filter(AppointmentDate - today() > -1) %>%
left_join(bookedSlots, by="AppointmentDate") %>%
replace_na(list(BookedSlots=0)) %>%
mutate(AvailableSlots=MaximumSlots - BookedSlots) %>%
filter(AvailableSlots > 0)
availableSlots
}
测试一下。请注意,在撰写本文时,01Apr2021 距离未来不到 14 天......
possibles <- findAvailableSlots(dmy("01Apr2021"))
possibles
# A tibble: 4 x 4
AppointmentDate MaximumSlots BookedSlots AvailableSlots
<date> <dbl> <dbl> <dbl>
1 2021-04-01 8 0 8
2 2021-03-31 8 0 8
3 2021-03-30 8 0 8
4 2021-03-29 8 0 8
预订一个插槽。为简单起见,只需取最后一个可用日期。
bookedAppointments <- bookedAppointments %>%
add_row(
AppointmentDate=possibles %>%
pull(AppointmentDate) %>%
head(1),
ParticipantID=1
)
bookedAppointments
# A tibble: 1 x 2
AppointmentDate ParticipantID
<date> <dbl>
1 2021-04-01 1
2021 年 4 月 1 日填补所有空缺
for (i in 2:8)
bookedAppointments <- bookedAppointments %>%
add_row(AppointmentDate=dmy("01Apr2021"), ParticipantID=i)
现在预约另一个约会
possibles <- findAvailableSlots(dmy("01Apr2021"))
bookedAppointments <- bookedAppointments %>%
add_row(
AppointmentDate=possibles %>% pull(AppointmentDate) %>% head(1),
ParticipantID=99
)
# A tibble: 9 x 2
AppointmentDate ParticipantID
<date> <dbl>
1 2021-04-01 1
2 2021-04-01 2
3 2021-04-01 3
4 2021-04-01 4
5 2021-04-01 5
6 2021-04-01 6
7 2021-04-01 7
8 2021-04-01 8
9 2021-03-31 99