[英]In R, is there a way to calculate the number of days between the end of one event and the beginning of another?
(注:酒店數據用作說明性示例。 )
我正在使用一個數據集,該數據集為每個客戶 (custID) 提供多條記錄(例如“hotelStays”)。 我的目標是將自客戶上次停留以來的天數作為數據框中的新列(即每個客戶的第一次停留將 'NA' 作為其價值)。 為此,我想從他們當前的 checkInDt 中減去每個客戶之前的 checkOutDt。 但是,當我嘗試使用 lag() 這樣做時,新列中的所有值都是“NA”。
下面是我正在使用的數據類型的示例。
客戶編號 | 逗留ID | 停留時間 | 簽入 | 簽出Dt |
---|---|---|---|---|
AAAAA | 11111 | 01/15/1995 | 01/10/1995 | 01/17/1995 |
BBBB | 11112 | 02/08/1995 | 02/02/1995 | 02/25/1995 |
AAAAA | 11113 | 03/01/1995 | 03/01/1995 | 03/03/1995 |
AAAAA | 11114 | 06/24/1995 | 06/22/1995 | 07/02/1995 |
BBBB | 11115 | 10/02/1995 | 10/01/1995 | 10/10/1995 |
中國交建 | 11116 | 01/08/1996 | 01/05/1996 | 01/17/1996 |
AAAAA | 11117 | 05/15/1996 | 05/10/1996 | 05/28/1996 |
理想情況下,新列“daysSinceLastStay”將具有以下值:
自上次入住以來的天數 |
---|
不適用 |
不適用 |
43 |
111 |
218 |
不適用 |
313 |
但是,我認為我需要先按 custID 和stayDt 排序。
以下是我目前對代碼的嘗試:
hotelData <- hotelData %>%
arrange(custID, stayDt) %>%
mutate(daysSinceLastStay =
checkInDt - lag(checkOutDt))
任何意見是極大的贊賞!
根據您期望的數據,您似乎需要使用group_by()
函數。 這應該能讓你找到你想要的東西。
# t*r*ibble, for creating data by row
hotelData <- tibble::tribble(
~custID, ~stayID, ~stayDt, ~checkInDt, ~checkOutDt,
"AAAAA", 11111, "01/15/1995", "01/10/1995", "01/17/1995",
"BBBBB", 11112, "02/08/1995", "02/02/1995", "02/25/1995",
"AAAAA", 11113, "03/01/1995", "03/01/1995", "03/03/1995",
"AAAAA", 11114, "06/24/1995", "06/22/1995", "07/02/1995",
"BBBBB", 11115, "10/02/1995", "10/01/1995", "10/10/1995",
"CCCCC", 11116, "01/08/1996", "01/05/1996", "01/17/1996",
"AAAAA", 11117, "05/15/1996", "05/10/1996", "05/28/1996"
)
# convert the date columns to the proper data type
# then, sort the data by customer ID and stayID
hotelData <- hotelData %>%
mutate(across(stayDt:checkOutDt, lubridate::mdy)) %>%
arrange(custID, stayID)
# within each customer, take the difference in days
hotelData %>%
group_by(custID) %>%
mutate(daysSinceLastStay = as.numeric(checkInDt - lag(checkOutDt)))
# A tibble: 7 x 6
# Groups: custID [3]
custID stayID stayDt checkInDt checkOutDt daysSinceLastStay
<chr> <dbl> <date> <date> <date> <dbl>
1 AAAAA 11111 1995-01-15 1995-01-10 1995-01-17 NA
2 AAAAA 11113 1995-03-01 1995-03-01 1995-03-03 43
3 AAAAA 11114 1995-06-24 1995-06-22 1995-07-02 111
4 AAAAA 11117 1996-05-15 1996-05-10 1996-05-28 313
5 BBBBB 11112 1995-02-08 1995-02-02 1995-02-25 NA
6 BBBBB 11115 1995-10-02 1995-10-01 1995-10-10 218
7 CCCCC 11116 1996-01-08 1996-01-05 1996-01-17 NA
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.