【发布时间】:2021-11-10 22:04:18
【问题描述】:
我正在使用 R 编程语言。假设有一家酒店有一个客户列表,上面有他们的入住和退房时间(注:日期的实际值是“POSIXct”,写成“年-月-日”。):
check_in_date <- c('2010-01-01', '2010-01-02' ,'2010-01-01', '2010-01-08', '2010-01-08', '2010-01-15', '2010-01-15', '2010-01-16', '2010-01-19', '2010-01-22')
check_out_date <- c('2010-01-07', '2010-01-04' ,'2010-01-09', '2010-01-21', '2010-01-11', '2010-01-22', 'still in hotel as of today', '2010-01-20', '2010-01-25', '2010-01-29')
Person = c("John", "Smith", "Alex", "Peter", "Will", "Matt", "Tim", "Kevin", "Tom", "Adam")
hotel <- data.frame(check_in_date, check_out_date, Person )
数据看起来像这样:
check_in_date check_out_date Person
1 2010-01-01 2010-01-07 John
2 2010-01-02 2010-01-04 Smith
3 2010-01-01 2010-01-09 Alex
4 2010-01-08 2010-01-21 Peter
5 2010-01-08 2010-01-11 Will
6 2010-01-15 2010-01-22 Matt
7 2010-01-15 still in hotel as of today Tim
8 2010-01-16 2010-01-20 Kevin
9 2010-01-19 2010-01-25 Tom
10 2010-01-22 2010-01-29 Adam
问题:我试图在任何一天找出酒店里还有多少人。这看起来像这样(只是一个例子,与上述数据不对应):
day_of_the_year Number_of_people_currently_in_hotel
1 2010-01-01 1
2 2010-01-02 1
3 2010-01-03 2
4 2010-01-04 0
5 2010-01-05 5
6 2010-01-06 5
7 2010-01-07 2
8 2010-01-08 2
9 2010-01-09 8
我尝试通过 3 个步骤解决此问题:
第一步:我生成了一个包含从开始到结束的每个日期的列(例如,在本例中,假设有 31 天:从 2010 年 1 月开始到结束)
day_of_the_year = seq(as.Date("2010/1/1"), as.Date("2010/1/31"),by="day")
第二步:然后我确定了每天入住酒店的人数:
library(dplyr)
#create some indicator variable
hotel$event = 1
check_ins = hotel %>% group_by(check_in_date) %>% summarise(n = n())
check_in_date n
<chr> <int>
1 2010-01-01 2
2 2010-01-02 1
3 2010-01-08 2
4 2010-01-15 2
5 2010-01-16 1
6 2010-01-19 1
7 2010-01-22 1
第三步:然后我重复了类似的步骤来确定每天有多少人退房:
check_outs = hotel %>% group_by(check_out_date) %>% summarise(n = n())
check_out_date n
<chr> <int>
1 2010-01-04 1
2 2010-01-07 1
3 2010-01-09 1
4 2010-01-11 1
5 2010-01-20 1
6 2010-01-21 1
7 2010-01-22 1
8 2010-01-25 1
9 2010-01-29 1
10 still in hotel as of today 1
问题:现在,我不知道如何将上述 3 个步骤组合起来,以便我们可以了解每月每天有多少人入住酒店。有人可以告诉我怎么做吗?
谢谢!
注意:我发现了一个“类似”问题counting the number of people in the system in R,我目前正在尝试查看是否可以针对我的问题调整此问题中使用的方法。
【问题讨论】:
标签: r dplyr group-by count data-manipulation