我如何计算R中两个日期之间每月的夜数,即使它们跨越两个月



我有酒店预订数据,有到达和离开日期。我已经成功地使用difftime计算了中间的天数,但我现在想知道每个月的日期数。如果抵达和出发日期都在一个月内(比如9月1日抵达和9月10日出发(,这当然不是问题,但我该如何处理跨月的预订,比如9月25日抵达和10月4日出发,甚至几年?在这种情况下,我想计算一下九月有多少天,十月有多少天。

总体目标是计算每月/每年的预订天数。

由于您没有包含样本数据(我可以建议您在下一个问题中这样做吗(,我制作了它来复制您想要的:

library(lubridate)
library(tidyverse)
#creating sample data
bookings <- tibble(
pax = c("Jane", "John"),
arrival = as.Date(c("2020-12-20", "2021-01-25")),
departure = as.Date(c("2021-01-04", "2021-02-02"))
)
#creating a column with all booked dates to group_by and summarize
bookings <- bookings %>% 
rowwise() %>% 
mutate(booked_dates = list(seq(arrival, departure, by="days"))) %>% # this creates a column of tiny dataframes with the occupied dates by pax
unnest(cols = booked_dates) %>% # this flattens the list-column into a regular one 
mutate( # extracting the year and month
year = year(booked_dates),
month = month(booked_dates, label = TRUE)
) %>% 
group_by(year, month) %>% # grouping and summarizing
summarise(n_days = n())

然后你就有了想要的输出:

bookings
# A tibble: 3 × 3
# Groups:   year [2]
year month n_days
<dbl> <ord>  <int>
1  2020 Dec       12
2  2021 Jan       11
3  2021 Feb        2

最新更新