Skip to content

Instantly share code, notes, and snippets.

@vsbuffalo
Created November 8, 2013 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsbuffalo/7378986 to your computer and use it in GitHub Desktop.
Save vsbuffalo/7378986 to your computer and use it in GitHub Desktop.
Example of GenomicRanges's tileGenome, which I think demonstrates its power. This might be a bit faster as a custom script in Python or C, but (1) this would take longer and (2) this is much more interactive (3) on real data, it's actually pretty fast. Stuff like this is why Bioconductor should be in every bioinformatician's toolkit.
library(GenomicRanges)
summarizeByTile <-
# given a GRanges (or some sort of ranged data) object `x`, and a
# *corresponding* vector values to summarize `y` (these *must*
# correspond), calculate the summary per tile with the function `fun`.
# Note: this is still beta; wider tests coming, use with caution.
function(x, y, tiles, fun, mcol_name="y") {
stopifnot(length(x) == length(y))
if (is(tiles, "GRangesList"))
tiles <- unlist(tiles)
# find overlaps between ranges object x and tiles
hits <- findOverlaps(x, tiles)
message(sprintf("summarizeByTile: %d overlaps found between x (%d rows) and genome tiles (%d rows)",
length(hits), length(x), length(tiles)))
# split y by hits in tiles
split_y <- split(y[queryHits(hits)], subjectHits(hits))
if (!is.null(mcol_name)) {
tile_summaries <- tiles[unique(subjectHits(hits))]
mcols(tile_summaries)[mcol_name] <- sapply(split_y, fun)
return(tile_summaries)
} else
sapply(split_y, fun)
}
# toy example
chr1_length <- c(chr1=1000)
tiles <- tileGenome(chr1_length, tilewidth=100)
snps <- GRanges("chr1", IRanges(sample(seq_len(chr1_length)), width=1), genotype=sample(c("0/0", "0/1", "1/1"), chr1_length, replace=TRUE))
tile_hets <- summarizeByTile(snps, mcols(snps)$genotype, tiles, fun=function(x) sum("0/1" == x)/length(x))
## > tile_hets
## > summarizeByTile(snps, mcols(snps)$genotype, tiles, fun=function(x) sum("0/1" == x)/length(x))
## summarizeByTile: 1000 overlaps found between x (1000 rows) and genome tiles (10 rows)
## GRanges with 10 ranges and 1 metadata column:
## seqnames ranges strand | y
## <Rle> <IRanges> <Rle> | <numeric>
## [1] chr1 [101, 200] * | 0.31
## [2] chr1 [801, 900] * | 0.31
## [3] chr1 [901, 1000] * | 0.43
## [4] chr1 [401, 500] * | 0.3
## [5] chr1 [601, 700] * | 0.42
## [6] chr1 [701, 800] * | 0.31
## [7] chr1 [201, 300] * | 0.28
## [8] chr1 [501, 600] * | 0.34
## [9] chr1 [301, 400] * | 0.28
## [10] chr1 [ 1, 100] * | 0.35
## ---
## seqlengths:
## chr1
## 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment