R - 绘制重叠时间间隔

Tim*_* S. 8 plot datetime r

我有一份人员名单以及他们一天的工作开始和结束时间.我想绘制一条曲线,显示当天任何一分钟工作的人员总数.我能做的就是为一天中的每一分钟添加1440个额外的条件布尔变量并总结它们,但这看起来非常不优雅.我想知道是否有更好的方法(积分?).

这是使用我的示例数据生成df的代码:

sample_wt <- function() {

    require(lubridate)

    set.seed(10)

    worktime <- data.frame(
            ID = c(1:100),
            start = now()+abs(rnorm(100,4800,2400))
            )

    worktime$end <- worktime$start + abs(rnorm(100,20000,10000))

    worktime$length <- difftime(worktime$end, worktime$start, units="mins")

    worktime
}
Run Code Online (Sandbox Code Playgroud)

要创建示例数据,您可以执行以下操作:

DF <- sample_wt() 
Run Code Online (Sandbox Code Playgroud)

ags*_*udy 5

这里有一个使用IRangesBioconductor包的选项 .

library(IRanges)
## generate sample
DF <- sample_wt()
## create the range from the sample data
rangesA <- IRanges(as.numeric(DF$start), as.numeric(DF$end))
## create one minute range 
xx = seq(min(DF$start),max(DF$end),60)
rangesB <- IRanges(as.numeric(xx),as.numeric(xx+60))
## count the overlaps
ov <- countOverlaps(rangesB, rangesA, type="within")
## plot the result
plot(xx,ov,type='l')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述