[英]How can I calculate the number of months between two given dates ( baseline and follow-up)
[英]How can I calculate the number of nights PER MONTH between two dates in R even if they are across two months?
我有酒店預訂數據,還有到達和離開日期。 我已經成功計算了使用 difftime 之間的天數,但我現在想知道每月的日期數。 如果到達和離開日期都在一個月內(例如 9 月 1 日到達和 9 月 10 日出發),那當然不是問題,但是對於像 9 月 25 日到達和 10 月 4 日出發這樣的跨月預訂,我該怎么辦?甚至幾年? 在這種情況下,我想計算 9 月有多少天,10 月有多少天。
總體目標是計算每月/每年的預訂天數。
由於您沒有包含示例數據(我可以建議您在下一個問題中這樣做),因此我做了它來復制您想要的內容:
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())
然后你就有了想要的 output:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.