Skip to content

Instantly share code, notes, and snippets.

@jalapic
Last active August 29, 2015 14:23
Show Gist options
  • Save jalapic/55665c45797dc2ee7da6 to your computer and use it in GitHub Desktop.
Save jalapic/55665c45797dc2ee7da6 to your computer and use it in GitHub Desktop.
# Binning Timed Event Data
# needs >=1.9.5 version of data.table
df_bin<-function(df,b=0,e=1200,interval=60){
library(data.table)
colnames(df)<-c("start", "end")
dt<-data.table(df)
lookup = data.table(start = seq(b, (e-interval), by = interval), end = seq(interval, e, by = interval))
ans = foverlaps(lookup, setkey(dt, start, end))
tmp<-ans[, sum(pmin(i.end, end) - pmax(i.start, start)), by=.(i.start,i.end)]
tmp[is.na(tmp)]<-0
colnames(tmp)<-c("start","end","duration")
return(tmp)
}
set.seed(1)
df<-
data.frame(start=c(2.3, 3.5,6.7,9.4,10.4,13.5,16.3,18.1),
duration=runif(8,0,1))
df$end<-df$start+df$duration
df$duration<-NULL
df
dt_out<-df_bin(df,b=0,e=20,interval=2); dt_out
dt_out<-df_bin(df,b=0,e=20,interval=5); dt_out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment