簡體   English   中英

我如何計算 R 中兩個日期之間每個月的夜數,即使它們跨越兩個月?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM