Skip to content
Prev 363605 / 398502 Next

Storing business hours

The cummax(+-1) trick, along with findInterval(), is most useful for
expanding a list of opening and closing times into a table which can be
used to find the number of open shops at any given time.  E.g., suppose
your raw data comes from business hours posted on web sites:

shopHours <- list(Butcher=rbind(c(Open=8,Close=12), c(13, 17)),
                  Florist=rbind(c(Open=10,Close=18)),
                  Pub=rbind(c(Open=10,Close=14), c(16,22)),
                  Bank=rbind(c(Open=9,Close=15)))

Then you can generate a list of the number of open shops at any time with:

d <- data.frame(Shop=rep(names(shopHours), vapply(shopHours,nrow,0)),
do.call("rbind", shopHours))
d <- with(d, rbind(data.frame(Shop, Hour=Open, Action=+1), data.frame(Shop,
Hour=Close, Action=-1)))
d <- d[order(d$Hour),]
d$NumberOpen <- cumsum(d$Action)
transform(data.frame(Hour=seq(8,22,by=1),
NumberOpen=d$NumberOpen[findInterval(Hour, d$Hour)])
#   Hour NumberOpen
#1     8          1
#2     9          2
#3    10          4
#4    11          4
#5    12          3
#6    13          4
#...


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Mon, Aug 29, 2016 at 8:06 AM, alexander.sommer at tu-dortmund.de <
alexander.sommer at tu-dortmund.de> wrote: