如何在R中得到类似直方图的区间数据摘要?
我的MWE数据有四个间隔。
interval range
Int1 2-7
Int2 10-14
Int3 12-18
Int4 25-28我想要一个类似直方图的函数,计算间隔Int1-Int4如何跨越一个在固定大小的垃圾箱之间分割的范围。函数输出应该如下所示:
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],有6个大小= 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但我仍然无法得到哪些是重叠的范围。如果我通过了就会更新。
发布于 2015-06-22 21:28:13
使用IRanges,您应该使用findOverlaps或mergeByOverlaps而不是countOverlaps。默认情况下,它不返回任何匹配项。
我会把这个留给你。相反,将显示使用来自foverlaps()包的data.table的替代方法:
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 int4https://stackoverflow.com/questions/30978837
复制相似问题