间隔数据的类似直方图的摘要

Histogram-like summary for interval data

如何在 R 中获得类似直方图的区间数据摘要?

我的 MWE 数据有四个区间。

interval  range
Int1      2-7
Int2      10-14
Int3      12-18
Int4      25-28

我想要一个类似直方图的函数,它计算间隔 Int1-Int4 如何跨越固定大小的 bin 的范围。 函数输出应如下所示:

bin     count  which
[0-4]   1      Int1
[5-9]   1      Int1
[10-14] 2      Int2 and Int3
[15-19] 1      Int3
[20-24] 0      None
[25-29] 1      Int4

这里的范围是 [minfloor(Int1, Int2, Int3, Int40), maxceil(Int1, Int2, Int3, Int4)) = [0,30) 并且有六个 bin 的大小 = 5.

我将非常感谢任何指向实现我想要的功能的 R 包或函数的指针。

更新:

到目前为止,我有一个来自 IRanges 包的解决方案,它使用称为 NCList 的快速数据结构,根据用户的说法,它比区间搜索树更快。

> library(IRanges)
> subject <- IRanges(c(2,10,12,25), c(7,14,18,28))
> query <- IRanges(c(0,5,10,15,20,25), c(4,9,14,19,24,29))
> countOverlaps(query, subject)
[1] 1 1 2 1 0 1

但我仍然无法得到重叠的范围。如果我通过会更新。

使用 IRanges,您应该使用 findOverlapsmergeByOverlaps 而不是 countOverlaps。不过,默认情况下,它 return 没有匹配项

我会把它留给你。相反,将显示使用 data.table 包中的 foverlaps() 的替代方法:

require(data.table)
subject <- data.table(interval = paste("int", 1:4, sep=""), 
                      start = c(2,10,12,25), 
                      end = c(7,14,18,28))
query <- data.table(start = c(0,5,10,15,20,25), 
                    end = c(4,9,14,19,24,29))

setkey(subject, start, end)
ans = foverlaps(query, subject, type="any")
ans[, .(count = sum(!is.na(start)), 
        which = paste(interval, collapse=", ")), 
     by = .(i.start, i.end)]

#    i.start i.end count      which
# 1:       0     4     1       int1
# 2:       5     9     1       int1
# 3:      10    14     2 int2, int3
# 4:      15    19     1       int3
# 5:      20    24     0         NA
# 6:      25    29     1       int4