将数据框拆分为大小相等的重叠组

时间:2018-04-23 08:01:21

标签: r iranges genomicranges

我正在寻找一种方法将数据拆分成组,其中每个组都由我定义的相同窗口大小组成。

      Chrom     Start   End        
      chr1       1    10      
      chr1       11   20      
      chr1       21   30      
      chr1       31   40 

例如,如果我想要一个20的窗口大小,那么这些组将是: 1-20,11-30,21-40。
只要该组的大小不超过20,它就可以继续添加到同一组中。

我尝试使用拆分功能,但无法使用它实现这种方式。 有办法解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

可以将矢量(或数据帧的列)拆分为重叠窗口,如下所示:

# Size of overlap
o <- 10
# Size of sliding window
n <- 20
# Dummy data
x <- sample(LETTERS, size = 40, replace = T)

# Define start and end point (s and e)
s <- 1
e <- n

# Loop to create fragments
for(i in 1:(length(x)/o)){

  assign(paste0("x", i), x[s:e])
  s <- s + o
  e <- (s + n) - 1

  }

# Call fragments  
x1
x2
x3

结果:

> x
 [1] "F" "E" "G" "X" "R" "S" "L" "F" "F" "C" "I" "X" "A" "C" "B" "Z" "Q" "T" "W" "L" "G" "I" "B" "I" "O" "V" "J" "Z" "C" "R" "W" "Z" "F" "T" "N" "U" "F" "R" "A" "V"
> x1
 [1] "F" "E" "G" "X" "R" "S" "L" "F" "F" "C" "I" "X" "A" "C" "B" "Z" "Q" "T" "W" "L"
> x2
 [1] "I" "X" "A" "C" "B" "Z" "Q" "T" "W" "L" "G" "I" "B" "I" "O" "V" "J" "Z" "C" "R"

答案 1 :(得分:0)

library(IRanges)
library(GenomicRanges)

(gr1 <- GRanges("chr1",IRanges(c(1,11,21,31),width=10),strand="*"))
(gr2 <- GRanges("chr1",IRanges(c(1,11,21),width=20),strand="*"))


fo <- findOverlaps(gr1, gr2)
queryHits(fo)
subjectHits(fo)

查看http://genomicsclass.github.io/book/pages/bioc1_igranges.html#intrarange了解详情。