在将基因组分割成相邻的不重叠的bin之后,例如通过tileGenome,我已经通过某种方法为每个bin(例如1或2)计算了一些属性。
现在,我想合并具有相同属性的相邻对象。下面是一个最小的例子:
library(GenomicRanges)
chrSizes <- c(chr1 = 1000, chr2 = 500)
bins <- tileGenome(chrSizes, tilewidth = 200, cut.last.tile.in.chrom = T)
bins$property <- rep(1:2, each = 4)
bins
GRanges object with 8 ranges and 1 metadata column:
seqnames ranges strand | property
<Rle> <IRanges> <Rle> | <integer>
[1] chr1 1-200 * | 1
[2] chr1 201-400 * | 1
[3] chr1 401-600 * | 1
[4] chr1 601-800 * | 1
[5] chr1 801-1000 * | 2
[6] chr2 1-200 * | 2
[7] chr2 201-400 * | 2
[8] chr2 401-500 * | 2
-------
seqinfo: 2 sequences from an unspecified genome前4个bin的属性为1,因此应该合并到一个bin中。
我浏览了GRanges文档,但找不到明显的本机解决方案。请注意,必须考虑seqname边界(例如,无论属性如何,chr1和chr2保持分离)显然,我可以使用循环,但我更喜欢使用原生GRange解决方案,例如使用我可能会监督的union。
所需的输出应如下所示:
seqnames ranges strand | property
<Rle> <IRanges> <Rle> | <integer>
[1] chr1 1-800 * | 1
[2] chr1 801-1000 * | 2
[3] chr2 1-500 * | 2发布于 2019-11-15 21:49:00
R GenomicRanges:
result <- unlist(reduce(split(bins, ~property)))
result$property <- names(result)
# GRanges object with 3 ranges and 1 metadata column:
# seqnames ranges strand | property
# <Rle> <IRanges> <Rle> | <character>
# 1 chr1 1-800 * | 1
# 2 chr1 801-1000 * | 2
# 2 chr2 1-500 * | 2
# -------
# seqinfo: 2 sequences from an unspecified genomePython PyRanges:
import pandas as pd
from io import StringIO
import pyranges as pr
c = """Chromosome Start End Value
chr1 1 200 Python
chr1 201 400 Python
chr1 401 600 Python
chr1 601 800 Python
chr1 801 1000 R
chr2 1 200 R
chr2 201 400 R
chr2 401 500 R"""
df = pd.read_table(StringIO(c), sep=" ")
gr = pr.PyRanges(df)
gr.merge(by="Value", slack=1)
# +--------------+-----------+-----------+------------+
# | Chromosome | Start | End | Value |
# | (category) | (int32) | (int32) | (object) |
# |--------------+-----------+-----------+------------|
# | chr1 | 1 | 800 | Python |
# | chr1 | 801 | 1000 | R |
# | chr2 | 1 | 500 | R |
# +--------------+-----------+-----------+------------+
# Unstranded PyRanges object has 3 rows and 4 columns from 2 chromosomes.
# For printing, the PyRanges was sorted on Chromosome.https://stackoverflow.com/questions/58876687
复制相似问题