calculating the number of "open hours" per day between two dates

I have a data frame with start dates and end dates, along with the number of people registered for an event. I would like to calculate the number of hours each party is present for within a specific timeframe (e.g., 07:00 - 17:00)

If I use the following example data.frame...

d <- data.frame(startDate = c(as.POSIXct("2011-06-04 08:00:00"), as.POSIXct("2011-06-03 08:00:00"),
                          as.POSIXct("2011-09-12 10:00:00")),
            endDate = c(as.POSIXct("2011-06-06 11:00:00"), as.POSIXct("2011-06-04 11:00:00"),
                        as.POSIXct("2011-09-12 18:00:00")),
            partysize = c(124,442,323))
open <- "07:00"
close <- "17:00"

I would like my result set to look something like this:

day                     numhours  partysize
2011-06-04                     9        124
2011-06-05                    10        124
2011-06-06                     4        124
2011-06-03                     9        442
2011-06-04                     4        442
2011-09-12                     7        323

note: numhours is the number of hours the date was included between the open and close times

Thanks in advance, --JT

Answers


Sorry its very messy and I used 7 and 17 instead of your open and close

app.days<-mapply(function(x,y){x+y*60*60*24},as.POSIXct(format(d$startDate,"%Y-%m-%d")),lapply(floor(-(d$startDate-d$endDate)/24),seq,from=0))
start.date<-mapply(function(x,y){pmax(x+7*60*60,y)},app.days,d$startDate)
end.date<-mapply(function(x,y){pmin(x+17*60*60,y)},app.days,d$endDate)
app.hours<-mapply(function(x,y){as.numeric(x-y)},end.date,start.date)
res<-mapply(function(x,y,z){data.frame(day=as.Date(x),numhours=y,partysize=z)},app.days,app.hours,as.list(d$partysize))
res1<-data.frame(day=as.Date(unlist(res[1,]),origin="1970-01-01"),numhours=unlist(res[2,]),partysize=unlist(res[3,]))

> res1
         day numhours partysize
1 2011-06-04        9       124
2 2011-06-05       10       124
3 2011-06-06        4       124
4 2011-06-03        9       442
5 2011-06-04        4       442
6 2011-09-12        7       323

Basically we identify how many days each party size stays for. For a given day we find the applicable open and close. Then we subtract open from close. The dataframe is eventually formed but it could probably have been created in the res<- step.....


Need Your Help

Fastest way to write to multiple socket connections

performance actionscript-3 sockets optimization

I am using the following class to accept incoming connections from client applications - using the send function I want to write the same UTFBytes to each client at the same time - is this possible...

Make 'background-image' responsive with layout attributes?

css polymer flexbox

Using Polymer 1.0, I am trying to do a layout and make the CSS background-image be width 100% and height auto. Not sure how to go about this in a flex-box or polymer layout sort of way. I could use...