我有一组不同id的时间间隔。例如:
df <- data.frame(id=c(rep("a",4),rep("b",2),rep("c",3)), start=c(100,250,400,600,150,610,275,600,700), end=c(200,300,550,650,275,640,325,675,725))
每个ID的时间间隔不重叠,但不同ID的时间间隔可能会重叠。下面是一张图片:
plot(range(df[,c(2,3)]),c(1,nrow(df)),type="n",xlab="",ylab="",yaxt="n")
for ( ii in 1:nrow(df) ) lines(c(df[ii,2],df[ii,3]),rep(nrow(df)-ii+1,2),col=as.numeric(df$id[ii]),lwd=2)
legend("bottomleft",lwd=2,col=seq_along(levels(df$id)),legend=levels(df$id))
我需要的是两个函数: 1. 一个函数将这些区间取并集。对于上面的例子,它将返回这个data.frame:
union.df <- data.frame(id=rep("a,b,c",4), start=c(100,400,600,700), end=c(325,550,675,725))
- 一个函数将交叉的时间段进行比较,只有当所有id都在该时间段内时才保留该时间段。 对于上面的例子,它将返回以下数据框:
intersection.df <- data.frame(id="a,b,c", start=610, end=640)