[Solved] counting the number of people in the system in R


If I understand your question, here’s an example with fake data:

library(tidyverse)
library(lubridate)

# Fake data
set.seed(2)
dat = data.frame(id=1:1000, type=rep(c("A","B"), 500), 
                 arrival=as.POSIXct("2013-08-21 05:00:00") + sample(-10000:10000, 1000, replace=TRUE))
dat$departure =  dat$arrival + sample(100:5000, 1000, replace=TRUE)

# Times when we want to check how many people are still present
times = seq(round_date(min(dat$arrival), "hour"), ceiling_date(max(dat$departure), "hour"), "30 min")

# Count number of people present at each time
map_df(times, function(x) {
  dat %>% 
    group_by(type) %>% 
    summarise(Time = x,
              Count=sum(arrival < x & departure > x)) %>% 
    spread(type, Count) %>% 
    mutate(Total = A + B)
})
                  Time     A     B Total
                <dttm> <int> <int> <int>
 1 2013-08-21 02:00:00     0     0     0
 2 2013-08-21 02:30:00    26    31    57
 3 2013-08-21 03:00:00    54    53   107
 4 2013-08-21 03:30:00    75    81   156
 5 2013-08-21 04:00:00    58    63   121
 6 2013-08-21 04:30:00    66    58   124
 7 2013-08-21 05:00:00    55    60   115
 8 2013-08-21 05:30:00    52    63   115
 9 2013-08-21 06:00:00    57    62   119
10 2013-08-21 06:30:00    62    51   113
11 2013-08-21 07:00:00    60    67   127
12 2013-08-21 07:30:00    72    54   126
13 2013-08-21 08:00:00    66    46   112
14 2013-08-21 08:30:00    19    12    31
15 2013-08-21 09:00:00     1     2     3
16 2013-08-21 09:30:00     0     0     0
17 2013-08-21 10:00:00     0     0     0

0

solved counting the number of people in the system in R