2015-06-22 41 views
0

如何獲取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)和有六個倉的大小= 5.

我將非常感謝R包或函數,實現我想要的功能的任何指針。

更新:

到目前爲止,我已經從使用快速的數據結構,稱爲NCLIST,這比根據用戶區間檢索樹快IRanges包的解決方案。

> 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 

但我仍然無法得到哪些是重疊的範圍。如果通過,我會更新。

+1

你用'table'試過了嗎? – akrun

+0

我試過了表,但不能超越對每個範圍終點的查詢的天真執行,即如果j> k且i nandu

+0

您的預期輸出是基於輸入示例嗎?我會嘗試用'休息'來削減'''' – akrun

回答

1

使用IRanges,您應該使用findOverlapsmergeByOverlaps而不是countOverlaps。它,默認情況下,不會返回但不匹配

我會把它留給你。相反,將顯示使用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 
+0

任何對foverlaps速度的評論比。 IRanges? foverlaps是否使用像NCList這樣的特殊數據結構/算法? – nandu