Peaks, CpGs and promoters are places on a chromosome, not rows with names. This lesson builds GRanges objects, finds what overlaps what, and avoids the off-by-one and wrong-genome mistakes that give no error.
This lesson follows From cells to cell types, the single-cell project that closed Module 6.
Across six modules you have handled tables whose rows had names: genes, cells, patients. Epigenomics data are different, because their rows are places on the genome: a stretch of DNA bound by a protein, a single CpG that may be methylated, a window of a chromosome. To ask whether a binding site sits near a gene, you have to compare positions, not names. This module gives you the tools for that, then uses them on ChIP-seq peaks, DNA methylation and, to finish, on combining several omics layers at once.
Positions on a genome
A genomic range is a stretch of a chromosome, given by four things: the chromosome (called the seqname, short for sequence name), a start, an end and a strand. DNA is double stranded, and a gene is read from one strand only. Bioconductor writes the forward strand as +, the reverse strand as -, and * when the strand is unknown or does not matter, as for most ChIP-seq peaks.
Two rules decide whether two people describing "the same" range actually agree.
- Counting convention. Bioconductor counts from 1 and includes both ends: the range 100–149 covers 50 bases, the 100th to the 149th. This is called 1-based, closed. The BED file format, used by most genome browsers and command-line tools, counts from 0 and leaves out the end: the same 50 bases are written 99 149. That is 0-based, half-open.
- Genome build. The human reference genome has been revised several times. A position in build hg19 (also called GRCh37) is not the same place as that number in hg38 (GRCh38); for many genes the difference is tens of thousands of bases or more. Two sets of ranges can only be compared if they use the same build.
Neither mistake produces an error message. Mixing conventions shifts every range by one base; mixing builds gives overlaps that look plausible but are wrong.
IRanges and GRanges
IRanges stores plain integer intervals. GenomicRanges builds on it: its GRanges objects add seqnames, strand and any extra columns. Loading GenomicRanges loads IRanges too.
library(GenomicRanges) ir <- IRanges(start = c(1, 10, 25), end = c(5, 19, 30)) ir width(ir)
The width of 1–5 is 5, not 4: both ends are included. Now a GRanges of four made-up peaks, with a name and a score for each.
gr <- GRanges(
seqnames = c("chr1", "chr1", "chr2", "chr1"),
ranges = IRanges(start = c(100, 400, 250, 900), width = c(50, 120, 80, 60)),
strand = c("+", "-", "+", "*"),
name = c("peakA", "peakB", "peakC", "peakD"),
score = c(12.5, 30.1, 8.2, 19.7)
)
gr
mcols(gr)
gr[gr$score > 15]What this does
GRanges()takes the chromosome of each range, anIRangesof positions (here given as start and width), the strand, and then any named columns. Those extra columns are the metadata columns, printed to the right of the bar |.mcols(gr)returns the metadata columns as a table. A single column can be reached with$, just as in a data frame:gr$score.gr[gr$score > 15]keeps the ranges whose score is above 15. AGRangesbehaves like a vector, so it takes one index.start(),end(),width()andstrand()pull out the parts.
The last line of the printout is the seqinfo: the chromosomes the object knows about, their lengths and the genome build. Here it is empty. For real data it should name the build, because Bioconductor then refuses to compare objects whose builds disagree.
Overlaps, distances and the strand
The question asked most often of ranges is which ones overlap. Here are three made-up genes to test the peaks against.
genes <- GRanges(
seqnames = c("chr1", "chr1", "chr2"),
ranges = IRanges(start = c(80, 850, 1000), end = c(500, 1200, 1500)),
strand = c("+", "-", "+"),
gene = c("geneX", "geneY", "geneZ")
)
hits <- findOverlaps(gr, genes)
hits
countOverlaps(gr, genes)
subsetByOverlaps(gr, genes)
data.frame(peak = gr$name[queryHits(hits)], gene = genes$gene[subjectHits(hits)])What this does
findOverlaps(query, subject)returns a Hits object: pairs of index numbers, one row per overlapping pair. The first argument is the query, the second the subject: row 1 says peakA overlaps geneX.countOverlaps()gives, for each query range, how many subject ranges it touches.subsetByOverlaps()keeps the query ranges that touch at least one subject range: the usual way to filter peaks by a set of regions.queryHits()andsubjectHits()pull out the two columns of index numbers, which you can use to build a plain table of who overlaps whom.
Look again at peakB. It runs from 400 to 519 on chr1, and geneX runs from 80 to 500 on chr1: the positions clearly overlap, yet findOverlaps() did not report it. The reason is the strand. By default, a + range and a - range never overlap, because they are on different strands of the DNA. A * range overlaps both, which is why peakD matched the reverse-strand geneY.
findOverlaps(gr, genes, ignore.strand = TRUE) distanceToNearest(gr, genes, ignore.strand = TRUE)
With ignore.strand = TRUE, peakB now overlaps geneX. Whether to ignore the strand is a biological question: a protein bound to DNA, as in ChIP-seq, sits on both strands, so peaks have no strand, while reads from a strand-specific RNA-seq library belong to one.
nearest() returns, for each query, the index of the closest subject range, and distanceToNearest() adds the gap in bases. A distance of 0 means the ranges overlap. peakC on chr2 ends at 329 and geneZ starts at 1,000, so the gap is 1,000 − 329 − 1 = 670 bases between them: the bases from 330 to 999. Ranges on different chromosomes are never near each other.
Worked example · one site, two coordinate systems
A BED file line reads chr1 99 149 peakA. What does Bioconductor call it, and how wide is it?
Bioconductor (1-based, closed): start 99 + 1 = 100, end 149
width 149 − 100 + 1 = 50
the same 50 bases: the 100th to the 149th
Step by step. In BED, the first base of a chromosome is base 0 and the end coordinate is the first base not included. So start 99 is the 100th base, and the range stops just before base 149 in 0-based counting, which is the 149th base in 1-based counting. To convert BED to Bioconductor, add 1 to the start and keep the end. To convert back, subtract 1 from the start.
What the answer means. Only the start moves. rtracklayer::import(), below, converts for you; read.table() does not.
Making new ranges from old ones
Many questions need a range derived from another: the region just upstream of a gene, the centre of a peak, a set of overlapping intervals merged into one. GenomicRanges has a function for each, and they all respect the strand.
promoters(genes, upstream = 100, downstream = 20)
flank(genes, width = 50)
resize(gr, width = 20, fix = "center")
overlapping <- GRanges("chr1", IRanges(start = c(100, 130, 300), end = c(150, 200, 350)))
reduce(overlapping)What this does
promoters(upstream = 100, downstream = 20)gives, for each gene, the 100 bases before its transcription start site (TSS), where the gene begins to be read, plus the first 20 bases of the gene. For a+gene the TSS is its start; for a-gene it is its end, because that strand is read from right to left. So geneY, which ends at 1,200, gets a promoter from 1,181 to 1,300.flank(width = 50)gives the 50 bases just before each gene, again on the correct side for its strand.resize(width = 20, fix = "center")trims every peak to 20 bases around its centre.fix = "start"would keep the start, which for a-range is the right-hand end.reduce()merges ranges that overlap or touch into one. The first two ranges, 100–150 and 130–200, become 100–200.
The first promoter starts at −20: geneX begins at base 80, and 100 bases upstream of that runs off the start of the chromosome. Bioconductor warns about this with real genomes whose chromosome lengths it knows, and trim() cuts such ranges back to the chromosome. With hand-made objects there are no lengths, so it cannot tell.
Go deeper: the other set operations
disjoin() cuts overlapping ranges into the pieces they share, and gaps() returns the stretches between ranges. intersect(a, b) works base by base: it gives the bases covered by both, not the ranges of a that overlap b. To keep whole peaks, use subsetByOverlaps().
findOverlaps() also takes minoverlap (a minimum number of shared bases), maxgap (ranges within this distance count as overlapping) and type = "within".
Real genes from a TxDb, and a BED file
A TxDb package holds a genome's gene models: where every gene, transcript and exon lies. TxDb.Hsapiens.UCSC.hg38.knownGene holds the UCSC "known gene" models for hg38. Its gene IDs are Entrez Gene IDs, numbers such as 7157 for TP53, which org.Hs.eg.db, the database you used in Volcano plot and interpretation, translates into symbols.
library(TxDb.Hsapiens.UCSC.hg38.knownGene) txdb <- TxDb.Hsapiens.UCSC.hg38.knownGene g38 <- genes(txdb) length(g38) head(g38, 3) table(strand(g38)) prom38 <- promoters(g38, upstream = 2000, downstream = 200)
What this does
genes(txdb)returns one range per gene, from the start of its first transcript to the end of its last, on its own strand. The names of the ranges and thegene_idcolumn are Entrez IDs: gene 1 is A1BG, on the reverse strand of chr19.- The message says 2,169 genes were left out because their parts lie on both strands or on more than one chromosome, so no single range can describe them.
- The seqinfo now names the hg38 genome and its 711 sequences: the chromosomes, the circular mitochondrial genome and many small extra pieces of the reference.
promoters(g38, upstream = 2000, downstream = 200)defines each gene's promoter as 2,000 bases before its TSS and 200 after. There is no single correct promoter size, a point the next lesson returns to. When this ran, R warned that 8 of the promoters ran past the end of small extra sequences such as chrUn_KI270748v1;trim(prom38)clips them.
Last, a BED file. Real ones come from a peak caller or a collaborator; here four made-up sites near three well-known cancer genes are written to a temporary file. BED columns are chromosome, start, end, name, score and strand, separated by tabs.
library(rtracklayer)
bed_file <- tempfile(fileext = ".bed")
writeLines(c(
"chr17\t7668401\t7669690\tsiteA\t500\t-",
"chr17\t7687000\t7687600\tsiteB\t800\t-",
"chr12\t25205245\t25205900\tsiteC\t300\t-",
"chr7\t55019000\t55019400\tsiteD\t650\t+"
), bed_file)
peaks <- import(bed_file, format = "BED")
peaks
genome(peaks) <- "hg38"
library(org.Hs.eg.db)
ov <- findOverlaps(peaks, g38, ignore.strand = TRUE)
sym <- mapIds(org.Hs.eg.db, keys = g38$gene_id[subjectHits(ov)],
keytype = "ENTREZID", column = "SYMBOL")
data.frame(site = peaks$name[queryHits(ov)], gene = sym)
distanceToNearest(peaks, prom38, ignore.strand = TRUE)What this does
tempfile()makes a file name in R's temporary folder, andwriteLines()writes the lines into it; \t is a tab.import()from rtracklayer reads the BED file into aGRanges. Compare the first line: the file says start 7668401, the object says 7668402. The conversion from 0-based to 1-based was done for you; the ends are unchanged. The name and score columns became metadata columns.genome(peaks) <- "hg38"records the build. A BED file does not say which build it uses, so this is your job, and it should come from whoever made the file, not from a guess.findOverlaps()finds the genes each site touches,mapIds()turns their Entrez IDs into symbols, anddistanceToNearest()gives the gap to the nearest promoter.
The table has six rows for four sites, because a site can overlap more than one gene. siteB overlaps both TP53 and WRAP53, a gene that starts close to TP53 on the opposite strand, and siteC overlaps both KRAS and ETFRF1. Expect one-to-many results from findOverlaps(), and decide how to handle them before you count genes.
The distances separate the sites into two kinds. siteB and siteD sit on a promoter (distance 0): siteD at the start of EGFR, siteB at the start of TP53, which, being on the reverse strand, begins at its right-hand end. siteA lies inside the TP53 gene but 14,380 bases from the nearest promoter, and siteC is 8,083 bases from one. Being inside a gene and being at its promoter are different claims; the next lesson builds on that difference.
Common mistakes
- Reading a BED file with
read.table()and building a GRanges from it directly. Every start is then one base too early. Useimport(), or add 1 to the starts yourself. - Comparing ranges from different builds. hg19 peaks against hg38 genes give overlaps that look reasonable and are wrong. Record the build with
genome()on every object; Bioconductor then refuses to mix them.liftOver()in rtracklayer moves ranges between builds. - Mismatched chromosome names. UCSC writes chr1; Ensembl writes 1. Nothing overlaps if the names differ.
seqlevelsStyle(x) <- "UCSC"renames them. - Forgetting the strand. Strandless peaks against stranded genes need
ignore.strand = TRUE, or many real overlaps disappear.
The GenomicRanges infrastructure is described in Lawrence et al. 2013, "Software for computing and annotating genomic ranges" (PLOS Computational Biology), and Bioconductor in Huber et al. 2015, "Orchestrating high-throughput genomic analysis with Bioconductor" (Nature Methods). The BED format is defined by the UCSC Genome Browser; the GRCh38 assembly is described by Schneider et al. 2017 (Genome Research). In methods, name the genome build and the version of the gene models.
Further reading · Module 7Lawrence et al. 2013: GenomicRanges and the design of range-based analysis in Bioconductor. · All reading for this course
Check your understanding
1. A BED file line reads chr2 199 260. Which range does Bioconductor use for the same bases?
2. A ChIP-seq peak on strand * overlaps a gene on strand −. A peak on strand + covers the same bases. What does findOverlaps() report by default?
3. For a gene on the − strand from 5,000 to 9,000, where does promoters(upstream = 1000, downstream = 0) put the promoter?