Package version: BiocAnnotRes2015 1.0.0

Annotation Resources

Introduction

Annotation resources make up a significant proportion of the Bioconductor project[1]. And there are also a diverse set of online resources available which are accessed using specific packages. This walkthrough will describe the most popular of these resources and give some high level examples on how to use them.

Bioconductor annotation resources have traditionally been used near the end of an analysis. After the bulk of the data analysis, annotations would be used interpretatively to learn about the most significant results. But increasingly, they are also used as a starting point or even as an intermediate step to help guide a study that is still in progress. In addition to this, what it means for something to be an annotation is also becoming less clear than it once was. It used to be clear that annotations were only those things that had been established after multiple different studies had been performed (such as the primary role of a gene product). But today many large data sets are treated by communities in much the same way that classic annotations once were: as a reference for additional comparisons.

Another change that is underway with annotations in Bioconductor is in the way that they are obtained. In the past annotations existed almost exclusively as separate annotation packages[2,3,4]. Today packages are still an enormous source of annotations. The current release repository contains over eight hundred annotation packages. This table summarizes some of the more important classes of annotation objects that are often accessed using packages:

Object type example package name contents
OrgDb org.Hs.eg.db gene based info. for Homo sapiens
TxDb TxDb.Hsapiens.UCSC.hg19.knownGene transcriptome ranges for Homo sapiens
OrganismDb Homo.sapiens composite information for Homo sapiens
BSgenome BSgenome.Hsapiens.UCSC.hg19 genome sequence for Homo sapiens

But in spite of the popularity of annotation packages, annotations are increasingly also being pulled down from web services like biomaRt[5,6,7] or from the AnnotationHub[8]. And both of these represent enormous resources for annotation data.

In part because of the rapidly evolving landscape, it is currently impossible in a single document to cover every possible annotation or even every kind of annotation present in Bioconductor. So here we will instead go over the most popular annotation resources and describe them in a way intended to expose common patterns used for accessing them. The hope is that a user with this information will be able to make educated guesses about how to find and use additional resources that will inevitably be added later. Topics that will be covered will include the following:

Set Up

In this chapter we make use of several Bioconductor packages. You can install them with biocLite():

source("http://bioconductor.org/biocLite.R")
biocLite(c("AnnotationHub", "Homo.sapiens",
           "TxDb.Hsapiens.UCSC.hg19.knownGene", 
           "BSgenome.Hsapiens.UCSC.hg19", "biomaRt",
           "TxDb.Athaliana.BioMart.plantsmart22")) 

The usage of the installed packages will be described in detail within the Usage section.

Using AnnotationHub

The top of the list for learning about annotation resources is the relatively new AnnotationHub package[8]. The AnnotationHub was created to provide a convenient access point for end users to find a large range of different annotation objects for use with Bioconductor. Resources found in the AnnotationHub are easy to discover and are presented to the user as familiar Bioconductor data objects. Because it is a recent addition, the AnnotationHub allows access to a broad range of annotation like objects, some of which may not have been considered annotations even a few years ago. To get started with the AnnotationHub users only need to load the package and then create a local AnnotationHub object like this:

## snapshotDate(): 2015-05-26
library("AnnotationHub") 
ah <- AnnotationHub() 

The very 1st time that you call the AnnotationHub, it will create a cache directory on your system and download the latest metadata for the hubs current contents. From that time forward, whenever you download one of the hubs data objects, it will also cache those files in the local directory so that if you request the information again, you will be able to access it quickly.

The show method of an AnnotationHub object will tell you how many resources are currently accessible using that object as well as give a high level overview of the most common kinds of data present.

ah 
## AnnotationHub with 34881 records
## # snapshotDate(): 2015-05-26 
## # $dataprovider: BroadInstitute, UCSC, Ensembl, NCBI, Haemcode, Inparan...
## # $species: Homo sapiens, Mus musculus, Bos taurus, Pan troglodytes, Da...
## # $rdataclass: GRanges, BigWigFile, FaFile, OrgDb, ChainFile, Inparanoi...
## # additional mcols(): taxonomyid, genome, description, tags,
## #   sourceurl, sourcetype 
## # retrieve records with, e.g., 'object[["AH2"]]' 
## 
##             title                                               
##   AH2     | Ailuropoda_melanoleuca.ailMel1.69.dna.toplevel.fa   
##   AH3     | Ailuropoda_melanoleuca.ailMel1.69.dna_rm.toplevel.fa
##   AH4     | Ailuropoda_melanoleuca.ailMel1.69.dna_sm.toplevel.fa
##   AH5     | Ailuropoda_melanoleuca.ailMel1.69.ncrna.fa          
##   AH6     | Ailuropoda_melanoleuca.ailMel1.69.pep.all.fa        
##   ...       ...                                                 
##   AH47932 | Xiphophorus_maculatus.Xipmac4.4.2.dna_rm.toplevel.fa
##   AH47933 | Xiphophorus_maculatus.Xipmac4.4.2.dna_sm.toplevel.fa
##   AH47934 | Xiphophorus_maculatus.Xipmac4.4.2.dna.toplevel.fa   
##   AH47935 | Xiphophorus_maculatus.Xipmac4.4.2.ncrna.fa          
##   AH47936 | Xiphophorus_maculatus.Xipmac4.4.2.pep.all.fa

As you can see from the object above, there are a LOT of different resources available. So normally when you get an AnnotationHub object the 1st thing you want to do is to filter it to remove unwanted resources.

Fortunately, the AnnotationHub has several different kinds of metadata that you can use for searching and subsetting. To see the different categories all you need to do is to type the name of your AnnotationHub object and then tab complete from the ‘$’ operator. And to see all possible contents of one of these categories you can pass that value in to unique like this:

unique(ah$dataprovider) 
##  [1] "Ensembl"                              
##  [2] "EncodeDCC"                            
##  [3] "UCSC"                                 
##  [4] "Inparanoid8"                          
##  [5] "NCBI"                                 
##  [6] "NHLBI"                                
##  [7] "ChEA"                                 
##  [8] "Pazar"                                
##  [9] "NIH Pathway Interaction Database"     
## [10] "RefNet"                               
## [11] "Haemcode"                             
## [12] "GEO"                                  
## [13] "BroadInstitute"                       
## [14] "ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/"
## [15] "dbSNP"

One of the most valuable ways in which the data is labeled is according to the kind of R object that will be returned to you.

unique(ah$rdataclass) 
##  [1] "FaFile"           "GRanges"          "Inparanoid8Db"   
##  [4] "OrgDb"            "TwoBitFile"       "ChainFile"       
##  [7] "SQLiteConnection" "data.frame"       "biopax"          
## [10] "BigWigFile"       "ExpressionSet"    "VcfFile"

Once you have identified which sorts of metadata you would like to use to find your data of interest, you can then use the subset or query methods to reduce the size of the hub object to something more manageable. For example you could select only those records where the string ‘GRanges’ was in the metadata. As you can see GRanges are one of the more popular formats for data that comes from the AnnotationHub.

grs <- query(ah, "GRanges") 
grs 
## AnnotationHub with 17296 records
## # snapshotDate(): 2015-05-26 
## # $dataprovider: BroadInstitute, UCSC, Ensembl, Haemcode, Pazar, EncodeDCC
## # $species: Homo sapiens, Mus musculus, Bos taurus, Pan troglodytes, Ca...
## # $rdataclass: GRanges
## # additional mcols(): taxonomyid, genome, description, tags,
## #   sourceurl, sourcetype 
## # retrieve records with, e.g., 'object[["AH3166"]]' 
## 
##             title                                   
##   AH3166  | wgEncodeRikenCageSknshraCellPapTssHmm   
##   AH3912  | wgEncodeUwDgfTregwb78495824Hotspots     
##   AH3913  | wgEncodeUwDgfTregwb78495824Pk           
##   AH4368  | wgEncodeUwDnaseWi38PkRep1               
##   AH4369  | wgEncodeUwDnaseWi38PkRep2               
##   ...       ...                                     
##   AH47104 | Tupaia_belangeri.TREESHREW.80.gtf       
##   AH47105 | Tursiops_truncatus.turTru1.80.gtf       
##   AH47106 | Vicugna_pacos.vicPac1.80.gtf            
##   AH47107 | Xenopus_tropicalis.JGI_4.2.80.gtf       
##   AH47108 | Xiphophorus_maculatus.Xipmac4.4.2.80.gtf

Or you can use subsetting to only select for matches on a specific field

grs <- ah[ah$rdataclass == "GRanges",] 

The subset function is also provided.

orgs <- subset(ah, ah$rdataclass == "OrgDb") 
orgs 
## AnnotationHub with 1164 records
## # snapshotDate(): 2015-05-26 
## # $dataprovider: NCBI, ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/
## # $species: Escherichia coli, Anopheles gambiae, Macaca mulatta, Pan tr...
## # $rdataclass: OrgDb
## # additional mcols(): taxonomyid, genome, description, tags,
## #   sourceurl, sourcetype 
## # retrieve records with, e.g., 'object[["AH12818"]]' 
## 
##             title                                                    
##   AH12818 | org.Pseudomonas_mendocina_NK-01.eg.sqlite                
##   AH12819 | org.Streptomyces_coelicolor_A3(2).eg.sqlite              
##   AH12820 | org.Cricetulus_griseus.eg.sqlite                         
##   AH12821 | org.Streptomyces_cattleya_NRRL_8057_=_DSM_46488.eg.sqlite
##   AH12822 | org.Cavia_porcellus.eg.sqlite                            
##   ...       ...                                                      
##   AH46997 | org.Ce.eg.db.sqlite                                      
##   AH46998 | org.Xl.eg.db.sqlite                                      
##   AH46999 | org.Sc.sgd.db.sqlite                                     
##   AH47000 | org.Dr.eg.db.sqlite                                      
##   AH47001 | org.Pf.plasmo.db.sqlite

And if you really need access to all the metadata you can extract it as a DataFrame using mcols() like so:

meta <- mcols(ah) 

Also if you are a fan of GUI’s you can use the display method to look at your data in a browser and return selected rows back as a smaller AnnotationHub object like this:

sah <- display(ah) 

Calling this method will produce a web based interface like the one pictured here:

Once you have the AnnotationHub object pared down to a reasonable size, and are sure about which records you want to retrieve, then you only need to use the ‘[[’ operator to extract them. Using the ‘[[’ operator, you can extract by numeric index (1,2,3) or by AnnotationHub ID. If you choose to use the former, you simply extract the element that you are interested in. So for our chain example, you might just want to 1st one like this:

res <- grs[[1]] 
## require("GenomicRanges")
head(res, n=3) 
## GRanges object with 3 ranges and 5 metadata columns:
##       seqnames                 ranges strand |
##          <Rle>              <IRanges>  <Rle> |
##   [1]    chr11 [ 65266509,  65266572]      + |
##   [2]     chr1 [156675257, 156675415]      - |
##   [3]    chr10 [ 33247091,  33247233]      - |
##                                           name     score     level
##                                    <character> <integer> <numeric>
##   [1]  chr11:65266509:65266572:+:0.04:1.000000         0 20993.670
##   [2] chr1:156675257:156675415:-:0.35:1.000000         0 11580.471
##   [3]  chr10:33247091:33247233:-:0.32:1.000000         0  8098.093
##          signif    score2
##       <numeric> <integer>
##   [1]  3.36e-10         0
##   [2]  3.54e-10         0
##   [3]  3.82e-10         0
##   -------
##   seqinfo: 24 sequences (1 circular) from hg19 genome

Or you might have decided that you want to see the data for the green spotted pufferfish by that you spotted in the orgs subset under the name ‘AH13961’. That data could also be extracted like this:

rabbit <- orgs[["AH13960"]] 
## Loading required package: AnnotationDbi
## Loading required package: Biobase
## Welcome to Bioconductor
## 
##     Vignettes contain introductory material; view with
##     'browseVignettes()'. To cite Bioconductor, see
##     'citation("Biobase")', and for packages 'citation("pkgname")'.
## 
## 
## Attaching package: 'Biobase'
## 
## The following object is masked from 'package:AnnotationHub':
## 
##     cache
rabbit 
## OrgDb object:
## | DBSCHEMAVERSION: 2.1
## | DBSCHEMA: NOSCHEMA_DB
## | ORGANISM: Oryctolagus cuniculus
## | SPECIES: Oryctolagus cuniculus
## | CENTRALID: GID
## | TAXID: 9986
## | Db type: OrgDb
## | Supporting package: AnnotationDbi
## 
## Please see: help('select') for usage information

AnnotationHub exercises

Exercise 1: Use the AnnotationHub to extract UCSC data that is from Homo sapiens and also specifically from the hg19 genome. What happens to the hub object as you filter data at each step?

Exercise 2 Now that you have basically narrowed things down to the hg19 annotations from UCSC genome browser, lets get one of these annotations. Find the oreganno track and save it into a local variable.

[ Back to top ]

OrgDb objects

At this point you might be wondering: What is this OrgDb object about? OrgDb objects are one member of a family of annotation objects that all represent hidden data through a shared set of methods. So if you look closely at the rabbit object in the example above you can see that it contains data for the European rabbit Oryctolagus cuniculus (taxonomy ID = 9986). You can learn a little more about it by learning about the columns method.

columns(rabbit) 
##  [1] "ACCNUM"      "ALIAS"       "CHR"         "ENTREZID"    "EVIDENCE"   
##  [6] "EVIDENCEALL" "GENENAME"    "GID"         "GO"          "GOALL"      
## [11] "ONTOLOGY"    "ONTOLOGYALL" "PMID"        "REFSEQ"      "SYMBOL"     
## [16] "UNIGENE"

The columns method gives you a vector of data types that can be retrieved from the object that you call it on. So the above call indicates that there are several different data types that can be retrieved from the tetra object.

A very similar method is the keytypes method, which will list all the data types that can also be used as keys.

keytypes(rabbit) 
##  [1] "ACCNUM"      "ALIAS"       "ENTREZID"    "EVIDENCE"    "EVIDENCEALL"
##  [6] "GENENAME"    "GID"         "GO"          "GOALL"       "ONTOLOGY"   
## [11] "ONTOLOGYALL" "PMID"        "REFSEQ"      "SYMBOL"      "UNIGENE"

In many cases most of the things that are listed as columns will also come back from a keytypes call, but since these two things are not guaranteed to be identical, we maintain two separate methods.

Now that you can see what kinds of things can be used as keys, you can call the keys method to extract out all the keys of a given key type.

head(keys(rabbit, keytype="ENTREZID")) 
## [1] "100008570" "100008594" "100008595" "100008596" "100008597" "100008598"

This is useful if you need to get all the IDs of a particular kind but the keys method has a few extra arguments that can make it even more flexible. For example, using the keys method you could also extract the gene SYMBOLS that contain “COX” like this:

keys(rabbit, keytype="SYMBOL", pattern="COX") 
## [1] "ACOX1"  "ACOX2"  "ACOX3"  "COX1"   "COX2"   "COX3"   "COX4I1" "COX6A1"
## [9] "COX6B"

Or if you really needed an other keytype, you can use the column argument to extract the ENTREZ GENE IDs for those gene SYMBOLS that contain the string “COX”:

keys(rabbit, keytype="ENTREZID", pattern="COX", column="SYMBOL") 
## 'select()' returned 1:1 mapping between keys and columns
## [1] "100009549" "100327269" "100327270" "100328652" "100338450" "103347455"
## [7] "808229"    "808231"    "808233"

But often, you will really want to extract other data that matches a particular key or set of keys. For that there are two methods which you can use. The more powerful of these is probably select. Here is how you would look up the gene SYMBOL, and REFSEQ id for the entrez gene IDs “808231” and “808233”.

select(rabbit, keys=c("808231","808233"), columns=c("SYMBOL","REFSEQ"),
       keytype="ENTREZID") 
## 'select()' returned 1:1 mapping between keys and columns
##   ENTREZID SYMBOL      REFSEQ
## 1   808231   COX1 NP_007551.1
## 2   808233   COX2 NP_007552.1

When you call it, select will return a data.frame that attempts to fill in matching values for all the columns you requested. However, if you ask select for things that have a many to one relationship to your keys it can result in an expansion of the data object that is returned. For example, watch what happens when we ask for the GO terms for the same entrez gene ID:

select(rabbit, keys="808233", columns="GO", keytype="ENTREZID") 
## 'select()' returned 1:many mapping between keys and columns
##   ENTREZID         GO
## 1   808233 GO:0009409
## 2   808233 GO:0005507
## 3   808233 GO:0005739
## 4   808233 GO:0016021
## 5   808233 GO:0022904
## 6   808233 GO:0007595
## 7   808233 GO:0009055
## 8   808233 GO:0020037
## 9   808233 GO:0004129

Because there are about 9 GO terms associated with the gene “808233”, you end up with 9 rows in the data.frame… This can become problematic if you then ask for several columns that have a many to one relationship to the original key. If you were to do that, not only would the result multiply in size, it would also become really hard to use. A better strategy is to be selective when using select.

Sometimes you might want to look up matching results in a way that is simpler than the data.frame object that select returns. This is especially true when you only want to look up one kind of value per key. For these cases, we recommend that you look at the mapIds method. Lets look at what happens if request the same basic information as in our recent select call, but instead using the mapIds method:

mapIds(rabbit, keys=c("808231","808233"), column="GO", keytype="ENTREZID") 
##       808231       808233 
## "GO:0005743" "GO:0009409"

As you can see, the mapIds method allows you to simplify the result that is returned. And by default, mapIds only returns the 1st matching element for each key. But what if you really need all those GO terms returned when you call mapIds? Well then you can make use of the mapIds multiVals argument. There are several options for this argument, we have already seen how by default you can return only the ‘first’ element. But you can also return a ‘list’ or ‘CharacterList’ object, or you can ‘filter’ out or return ‘asNA’ any keys that have multiple matches. You can even define your own rule (as a function) and pass that in as an argument to multiVals. Lets look at what happens when you return a list:

mapIds(rabbit, keys=c("808231","808233"), column="GO", 
       keytype="ENTREZID", multiVals="list") 
## $`808231`
##  [1] "GO:0005743" "GO:0004129" "GO:0015992" "GO:0009055" "GO:0034220"
##  [6] "GO:0046688" "GO:0021549" "GO:0044281" "GO:0009060" "GO:0005515"
## [11] "GO:0007568" "GO:0016021" "GO:0020037" "GO:0006123" "GO:0051602"
## [16] "GO:0006979"
## 
## $`808233`
## [1] "GO:0009409" "GO:0005507" "GO:0005739" "GO:0016021" "GO:0022904"
## [6] "GO:0007595" "GO:0009055" "GO:0020037" "GO:0004129"

Now you know how to extract information from an OrgDb object, you might find it helpful to know that there is a whole family of other AnnotationDb derived objects that you can also use with these same five methods (keytypes(), columns(), keys(), select(), and mapIds()). For example there are ChipDb objects, InparanoidDb objects and TxDb objects which contain data about microarray probes, inparanoid homology partners or transcript range information respectively. And there are also more specialized objects like GODb or ReactomeDb objects which offer access to data from GO and reactome. In the next section, we will be looking at one of the more popular classes of these objects: the TxDb object.

OrgDb exercises

Exercise 3: Look at the help page for the different columns and keytypes values with: help(“SYMBOL”). Now use this information and what we just described to look up the entrez gene and chromosome for the gene symbol “MSX2”.

Exercise 4: In the previous exercise we had to use gene symbols as keys. But in the past this kind of behavior has sometimes been inadvisable because some gene symbols are used as the official symbol for more than one gene. To learn if this is still happening take advantage of the fact that entrez gene ids are uniquely assigned, and extract all of the gene symbols and their associated entrez gene ids from the org.Hs.eg.db package. Then check the symbols for redundancy.

[ Back to top ]

TxDb Objects

As mentioned before, TxDb objects can be accessed using the standard set of methods: keytypes(), columns(), keys(), select(), and mapIds(). But because these objects contain information about a transcriptome, they are often used to compare range based information to these important features of the genome[3,4]. As a result they also have specialized accessors for extracting out ranges that correspond to important transcriptome characteristics.

Lets start by loading a TxDb object from an annotation package based on the UCSC ensembl genes track for Drosophila. A common practice when loading these is to shorten the long name to ‘txdb’ (just as a convenience).

library("TxDb.Hsapiens.UCSC.hg19.knownGene")
## Loading required package: GenomicFeatures
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene
txdb
## TxDb object:
## # Db type: TxDb
## # Supporting package: GenomicFeatures
## # Data source: UCSC
## # Genome: hg19
## # Organism: Homo sapiens
## # TaxID: 9606
## # UCSC Table: knownGene
## # Resource URL: http://genome.ucsc.edu/
## # Type of Gene ID: Entrez Gene ID
## # Full dataset: yes
## # miRBase build ID: GRCh37
## # transcript_nrow: 82960
## # exon_nrow: 289969
## # cds_nrow: 237533
## # Db created by: GenomicFeatures package from Bioconductor
## # Creation time: 2015-05-12 10:59:39 -0700 (Tue, 12 May 2015)
## # GenomicFeatures version at creation time: 1.21.3
## # RSQLite version at creation time: 1.0.0
## # DBSCHEMAVERSION: 1.1

Just by looking at the TxDb object, we can learn a lot about what data it contains including where the data came from, which build of the UCSC genome it was based on and the last time that the object was updated. One of the most common uses for a TxDb object is to extract various kinds of transcript data out of it. So for example you can extract all the transcripts out of the TxDb as a GRanges object like this:

txs <- transcripts(txdb)
txs
## GRanges object with 82960 ranges and 2 metadata columns:
##           seqnames               ranges strand   |     tx_id     tx_name
##              <Rle>            <IRanges>  <Rle>   | <integer> <character>
##       [1]     chr1     [ 11874,  14409]      +   |         1  uc001aaa.3
##       [2]     chr1     [ 11874,  14409]      +   |         2  uc010nxq.1
##       [3]     chr1     [ 11874,  14409]      +   |         3  uc010nxr.1
##       [4]     chr1     [ 69091,  70008]      +   |         4  uc001aal.1
##       [5]     chr1     [321084, 321115]      +   |         5  uc001aaq.2
##       ...      ...                  ...    ... ...       ...         ...
##   [82956]     chrY [27605645, 27605678]      -   |     78803  uc004fwx.1
##   [82957]     chrY [27606394, 27606421]      -   |     78804  uc022cpc.1
##   [82958]     chrY [27607404, 27607432]      -   |     78805  uc004fwz.3
##   [82959]     chrY [27635919, 27635954]      -   |     78806  uc022cpd.1
##   [82960]     chrY [59358329, 59360854]      -   |     78807  uc011ncc.1
##   -------
##   seqinfo: 93 sequences (1 circular) from hg19 genome

Similarly, there are also extractors for exons(), cds(), genes() and promoters(). Which kind of feature you choose to extract just depends on what information you are after. These basic extractors are fine if you only want a flat representation of these data, but many of these features are inherently nested. So instead of extracting a flat GRanges object, you might choose instead to extract a GRangesList object that groups the transcripts by the genes that they are associated with like this:

txby <- transcriptsBy(txdb, by="gene")
txby
## GRangesList object of length 23459:
## $1 
## GRanges object with 2 ranges and 2 metadata columns:
##       seqnames               ranges strand |     tx_id     tx_name
##          <Rle>            <IRanges>  <Rle> | <integer> <character>
##   [1]    chr19 [58858172, 58864865]      - |     70455  uc002qsd.4
##   [2]    chr19 [58859832, 58874214]      - |     70456  uc002qsf.2
## 
## $10 
## GRanges object with 1 range and 2 metadata columns:
##       seqnames               ranges strand | tx_id    tx_name
##   [1]     chr8 [18248755, 18258723]      + | 31944 uc003wyw.1
## 
## $100 
## GRanges object with 1 range and 2 metadata columns:
##       seqnames               ranges strand | tx_id    tx_name
##   [1]    chr20 [43248163, 43280376]      - | 72132 uc002xmj.3
## 
## ...
## <23456 more elements>
## -------
## seqinfo: 93 sequences (1 circular) from hg19 genome

Just as with the flat extractors, there is a whole family of extractors available depending on what you want to extract and how you want it grouped. They include transcriptsBy(), exonsBy(), cdsBy(), intronsByTranscript(), fiveUTRsByTranscript() and threeUTRsByTranscript().

When dealing with genomic data it is almost inevitable that you will run into problems with the way that different groups have adopted alternate ways of naming chromosomes. This is because almost every major repository has cooked up their own slightly different way of labeling these important features.

To cope with this, the Seqinfo object was invented and is attached to TxDb objects as well as the GenomicRanges extracted from these objects. You can extract it using the seqinfo() method like this:

si <- seqinfo(txdb)
si
## Seqinfo object with 93 sequences (1 circular) from hg19 genome:
##   seqnames       seqlengths isCircular genome
##   chr1            249250621      FALSE   hg19
##   chr2            243199373      FALSE   hg19
##   chr3            198022430      FALSE   hg19
##   chr4            191154276      FALSE   hg19
##   chr5            180915260      FALSE   hg19
##   ...                   ...        ...    ...
##   chrUn_gl000245      36651      FALSE   hg19
##   chrUn_gl000246      38154      FALSE   hg19
##   chrUn_gl000247      36422      FALSE   hg19
##   chrUn_gl000248      39786      FALSE   hg19
##   chrUn_gl000249      38502      FALSE   hg19

And since the seqinfo information is also attached to the GRanges objects produced by the TxDb extractors, you can also call seqinfo on the results of those methods like this:

txby <- transcriptsBy(txdb, by="gene")
si <- seqinfo(txby)

The Seqinfo object contains a lot of valuable data about which chromosome features are present, whether they are circular or linear, and how long each one is. It is also something that will be checked against if you try to do an operation like ‘findOverlaps’ to compute overlapping ranges etc. So it’s a valuable way to make sure that the chromosomes and genome are the same for your annotations as the range that you are comparing them to. But sometimes you may have a situation where your annotation object contains data that is comparable to your data object, but where it is simply named with a different naming style. For those cases, there are helpers that you can use to discover what the current name style is for an object. And there is also a setter method to allow you to change the value to something more appropriate. So in the following example, we are going to change the seqlevelStyle from ‘UCSC’ to ‘ensembl’ based naming convention (and then back again).

head(seqlevels(txdb))
## [1] "chr1" "chr2" "chr3" "chr4" "chr5" "chr6"
seqlevelsStyle(txdb)
## [1] "UCSC"
seqlevelsStyle(txdb) <- "NCBI"
head(seqlevels(txdb))
## [1] "1" "2" "3" "4" "5" "6"
## then change it back
seqlevelsStyle(txdb) <- "UCSC"
head(seqlevels(txdb))
## [1] "chr1" "chr2" "chr3" "chr4" "chr5" "chr6"

In addition to being able to change the naming style used for an object with seqinfo data, you can also toggle which of the chromosomes are ‘active’ so that the software will ignore certain chromosomes. By default, all of the chromosomes are set to be ‘active’.

head(isActiveSeq(txdb), n=30)
##                 chr1                 chr2                 chr3 
##                 TRUE                 TRUE                 TRUE 
##                 chr4                 chr5                 chr6 
##                 TRUE                 TRUE                 TRUE 
##                 chr7                 chr8                 chr9 
##                 TRUE                 TRUE                 TRUE 
##                chr10                chr11                chr12 
##                 TRUE                 TRUE                 TRUE 
##                chr13                chr14                chr15 
##                 TRUE                 TRUE                 TRUE 
##                chr16                chr17                chr18 
##                 TRUE                 TRUE                 TRUE 
##                chr19                chr20                chr21 
##                 TRUE                 TRUE                 TRUE 
##                chr22                 chrX                 chrY 
##                 TRUE                 TRUE                 TRUE 
##                 chrM chr1_gl000191_random chr1_gl000192_random 
##                 TRUE                 TRUE                 TRUE 
##       chr4_ctg9_hap1 chr4_gl000193_random chr4_gl000194_random 
##                 TRUE                 TRUE                 TRUE

But sometimes you might wish to ignore some of them. For example, lets suppose that you wanted to ignore the Y chromosome from our txdb. You could do that like so:

isActiveSeq(txdb)["chrY"] <- FALSE
head(isActiveSeq(txdb), n=26)
##                 chr1                 chr2                 chr3 
##                 TRUE                 TRUE                 TRUE 
##                 chr4                 chr5                 chr6 
##                 TRUE                 TRUE                 TRUE 
##                 chr7                 chr8                 chr9 
##                 TRUE                 TRUE                 TRUE 
##                chr10                chr11                chr12 
##                 TRUE                 TRUE                 TRUE 
##                chr13                chr14                chr15 
##                 TRUE                 TRUE                 TRUE 
##                chr16                chr17                chr18 
##                 TRUE                 TRUE                 TRUE 
##                chr19                chr20                chr21 
##                 TRUE                 TRUE                 TRUE 
##                chr22                 chrX                 chrY 
##                 TRUE                 TRUE                FALSE 
##                 chrM chr1_gl000191_random 
##                 TRUE                 TRUE

TxDb exercises

Exercise 5: Use the accessors for the TxDb.Hsapiens.UCSC.hg19.knownGene package to retrieve the gene id, transcript name and transcript chromosome for all the transcripts. Do this using both the select() method and also using the transcripts() method. What is the difference in the output?

Exercise 6: Load the TxDb.Athaliana.BioMart.plantsmart22 package. This package is not from UCSC and it is based on plantsmart. Now use select or one of the range based accessors to look at the gene ids from this TxDb object. How do they compare to what you saw in the TxDb.Hsapiens.UCSC.hg19.knownGene package?

[ Back to top ]

OrganismDb Objects

So what happens if you have data from multiple different Annotation objects. For example, what if you had gene SYMBOLS (found in an OrgDb object) and you wanted to easily match those up with known gene transcript names from a UCSC based TxDb object? There is an ideal tool that can help with this kind of problem and it’s called an OrganismDb object[9]. On the one hand OrganismDb objects can seem more complex than OrgDb, GODb or TxDb objects because they can allow you to access all three object sources at once. But in reality they are not that complicated. What they do is just query each of these resources for you and then merge the results back together in way that lets you pretend that you only have one source for all your annotations.

To try one out lets load one that was made as an annotation package:

library("Homo.sapiens")
## Loading required package: OrganismDbi
## Loading required package: GO.db
## Loading required package: DBI
## 
## Loading required package: org.Hs.eg.db
## 
## Now getting the GODb Object directly
## Now getting the OrgDb Object directly
## Now getting the TxDb Object directly
Homo.sapiens
## OrganismDb Object:
## # Includes GODb Object:  GO.db 
## # With data about:  Gene Ontology 
## # Includes OrgDb Object:  org.Hs.eg.db 
## # Gene data about:  Homo sapiens 
## # Taxonomy Id:  9606 
## # Includes TxDb Object:  TxDb.Hsapiens.UCSC.hg19.knownGene 
## # Transcriptome data about:  Homo sapiens 
## # Based on genome:  hg19 
## # The OrgDb gene id ENTREZID is mapped to the TxDb gene id GENEID .

And that’s it. You can now use these objects in the same way that you use OrgDb or TxDb objects. It works the same as the base objects that it contains:

select(Homo.sapiens, keys="4488", columns=c("SYMBOL","TXNAME"), keytype="ENTREZID")
## 'select()' returned 1:1 mapping between keys and columns
##   ENTREZID SYMBOL     TXNAME
## 1     4488   MSX2 uc003mcy.3

In fact the five methods that worked for all of the other Db objects that we have discussed (keytypes(), columns(), keys(), select(), and mapIds()) should all work for OrganismDb objects. And if the OrganismDb object was composed to include a TxDb, then the range based accessors should also work:

txs <- transcripts(Homo.sapiens, columns=c("TXNAME","SYMBOL"))
## 'select()' returned 1:1 mapping between keys and columns
txs
## GRanges object with 82508 ranges and 2 metadata columns:
##           seqnames                 ranges strand   |          TXNAME
##              <Rle>              <IRanges>  <Rle>   | <CharacterList>
##       [1]     chr1       [ 11874,  14409]      +   |      uc001aaa.3
##       [2]     chr1       [ 11874,  14409]      +   |      uc010nxq.1
##       [3]     chr1       [ 11874,  14409]      +   |      uc010nxr.1
##       [4]     chr1       [ 69091,  70008]      +   |      uc001aal.1
##       [5]     chr1       [321084, 321115]      +   |      uc001aaq.2
##       ...      ...                    ...    ... ...             ...
##   [82504]     chrX [154686575, 154688276]      -   |      uc004fnj.3
##   [82505]     chrX [154689080, 154689596]      -   |      uc004fnk.3
##   [82506]     chrX [154718673, 154842622]      -   |      uc004fnn.3
##   [82507]     chrX [154722196, 154842622]      -   |      uc004fnp.4
##   [82508]     chrX [155255323, 155257848]      -   |      uc011nad.1
##                    SYMBOL
##           <CharacterList>
##       [1]         DDX11L1
##       [2]         DDX11L1
##       [3]         DDX11L1
##       [4]           OR4F5
##       [5]              NA
##       ...             ...
##   [82504]            F8A1
##   [82505]          H2AFB3
##   [82506]           TMLHE
##   [82507]           TMLHE
##   [82508]              NA
##   -------
##   seqinfo: 92 sequences (1 circular) from hg19 genome

But one key difference between the range accessors for a TxDb object when compared to an OrganismDb object is that the number of things that can be requested via columns is much greater for the compound object…

OrganismDb exercises

Exercise 7: Use the Homo.sapiens object to look up the gene symbol, transcript start and chromosome using select(). Then do the same thing using transcripts. You might expect that this call to transcripts will look the same as it did for the TxDb object, but (temporarily) it will not.

Exercise 8: Look at the results from call the columns method on the Homo.sapiens object and compare that to what happens when you call columns on the org.Hs.eg.db object and then look at a call to columns on the TxDb.Hsapiens.UCSC.hg19.knownGene object. What is the difference between TXSTART and CHRLOC? Which one do you think you should use for transcripts or other genomic information?

Exercise 9: Use the Homo.sapiens object with the keys method to look up the entrez gene IDs for all gene symbols that contain the letter “X”.

[ Back to top ]

BSgenome Objects

Another important annotation resource type is a BSgenome package[10]. There are many BSgenome packages in the repository for you to choose from. And you can learn which organisms are already supported by using the available.genomes() function.

library("BSgenome")
## Loading required package: Biostrings
## Loading required package: XVector
## Loading required package: rtracklayer
head(available.genomes())
## [1] "BSgenome.Alyrata.JGI.v1"                
## [2] "BSgenome.Amellifera.BeeBase.assembly4"  
## [3] "BSgenome.Amellifera.UCSC.apiMel2"       
## [4] "BSgenome.Amellifera.UCSC.apiMel2.masked"
## [5] "BSgenome.Athaliana.TAIR.04232008"       
## [6] "BSgenome.Athaliana.TAIR.TAIR9"

Unlike the other resources that we have discussed here, these packages are meant to contain sequence data for a specific genome build of an organism. You can load one of these packages in the usual way. And each of them normally has an alias for the primary object that is shorter than the full package name (as a convenience):

library("BSgenome.Hsapiens.UCSC.hg19")
ls(2)
## [1] "BSgenome.Hsapiens.UCSC.hg19" "Hsapiens"
Hsapiens
## Human genome:
## # organism: Homo sapiens (Human)
## # provider: UCSC
## # provider version: hg19
## # release date: Feb. 2009
## # release name: Genome Reference Consortium GRCh37
## # 93 sequences:
## #   chr1                  chr2                  chr3                 
## #   chr4                  chr5                  chr6                 
## #   chr7                  chr8                  chr9                 
## #   chr10                 chr11                 chr12                
## #   chr13                 chr14                 chr15                
## #   ...                   ...                   ...                  
## #   chrUn_gl000235        chrUn_gl000236        chrUn_gl000237       
## #   chrUn_gl000238        chrUn_gl000239        chrUn_gl000240       
## #   chrUn_gl000241        chrUn_gl000242        chrUn_gl000243       
## #   chrUn_gl000244        chrUn_gl000245        chrUn_gl000246       
## #   chrUn_gl000247        chrUn_gl000248        chrUn_gl000249       
## # (use 'seqnames()' to see all the sequence names, use the '$' or '[['
## # operator to access a given sequence)

The getSeq method is a useful way of extracting data from these packages. This method takes several arguments but the important ones are the 1st two. The 1st argument specifies the BSgenome object to use and the second argument (names) specifies what data you want back out. So for example, if you call it and give a character vector that names the seqnames for the object then you will get the sequences from those chromosomes as a DNAStringSet object.

seqNms <- seqnames(Hsapiens)
head(seqNms)
## [1] "chr1" "chr2" "chr3" "chr4" "chr5" "chr6"
getSeq(Hsapiens, seqNms[1:2])
##   A DNAStringSet instance of length 2
##         width seq
## [1] 249250621 NNNNNNNNNNNNNNNNNNNNNNNNNNNNN...NNNNNNNNNNNNNNNNNNNNNNNNNNNNN
## [2] 243199373 NNNNNNNNNNNNNNNNNNNNNNNNNNNNN...NNNNNNNNNNNNNNNNNNNNNNNNNNNNN

Whereas if you give the a GRanges object for the 2nd argument, you can instead get a DNAStringSet that corresponds to those ranges. This can be a powerful way to learn what sequence was present from a particular range. For example, here we can extract the range of a specific gene of interest like this.

txby <- transcriptsBy(txdb, by="gene")
geneOfInterest <- txby[["4488"]]
res <- getSeq(Hsapiens, geneOfInterest)
res
##   A DNAStringSet instance of length 1
##     width seq
## [1]  6328 TCCCGTCTCCGCAGCAAAAAAGTTTGAGTCG...TTGCAGTAAAGTTTGTCCAAACTCACAATTA

Additionally, the Biostrings[11] package has many useful functions for finding a pattern in a string set etc. You may not have noticed when it happened, but the Biostrings package was loaded when you loaded the BSgenome object, so these functions will already be available for you to explore.

BSgenome exercises

Exercise 10: Use what you have just learned to extract the sequence for the PTEN gene.

[ Back to top ]

biomaRt

Another great annotation resource is the biomaRt package[5,6,7]. The biomaRt package exposes a huge family of different online annotation resources called marts. Each mart is another of a set of online web resources that are following a convention that allows them to work with this package. So the first step in using biomaRt is always to load the package and then decide which “mart” you want to use. Once you have made your decision, you will then use the useMart() method to create a mart object in your R session. Here we are looking at the marts available and then choosing to use one of the most popular marts: the “ensembl”" mart.

library("biomaRt")
head(listMarts())
##               biomart                             version
## 1             ensembl        ENSEMBL GENES 80 (SANGER UK)
## 2                 snp    ENSEMBL VARIATION 80 (SANGER UK)
## 3          regulation   ENSEMBL REGULATION 80 (SANGER UK)
## 4                vega                VEGA 60  (SANGER UK)
## 5       fungi_mart_26           ENSEMBL FUNGI 26 (EBI UK)
## 6 fungi_variations_26 ENSEMBL FUNGI VARIATION 26 (EBI UK)
ensembl <- useMart("ensembl")
ensembl
## Object of class 'Mart':
##  Using the ensembl BioMart database
##  Using the  dataset

Each ‘mart’ can contain datasets for multiple different things. So the next step is that you need to decide on a dataset. Once you have chosen one, you will need to specify that dataset using the dataset argument when you call the useMart() constructor method. Here we will point to the dataset for humans.

head(listDatasets(ensembl))
##                          dataset
## 1         oanatinus_gene_ensembl
## 2        cporcellus_gene_ensembl
## 3        gaculeatus_gene_ensembl
## 4         lafricana_gene_ensembl
## 5 itridecemlineatus_gene_ensembl
## 6        choffmanni_gene_ensembl
##                                  description version
## 1     Ornithorhynchus anatinus genes (OANA5)   OANA5
## 2            Cavia porcellus genes (cavPor3) cavPor3
## 3     Gasterosteus aculeatus genes (BROADS1) BROADS1
## 4         Loxodonta africana genes (loxAfr3) loxAfr3
## 5 Ictidomys tridecemlineatus genes (spetri2) spetri2
## 6        Choloepus hoffmanni genes (choHof1) choHof1
ensembl <- useMart("ensembl",dataset="hsapiens_gene_ensembl")
ensembl
## Object of class 'Mart':
##  Using the ensembl BioMart database
##  Using the hsapiens_gene_ensembl dataset

Next we need to think about attributes, values and filters. Lets start with attributes. You can get a listing of the different kinds of attributes from biomaRt buy using the listAttributes method:

head(listAttributes(ensembl))
##                    name           description
## 1       ensembl_gene_id       Ensembl Gene ID
## 2 ensembl_transcript_id Ensembl Transcript ID
## 3    ensembl_peptide_id    Ensembl Protein ID
## 4       ensembl_exon_id       Ensembl Exon ID
## 5           description           Description
## 6       chromosome_name       Chromosome Name

And you can see what the values for a particular attribute are by using the getBM method:

head(getBM(attributes="chromosome_name", mart=ensembl))
##   chromosome_name
## 1               1
## 2              10
## 3              11
## 4              12
## 5              13
## 6              14

Attributes are the things that you can have returned from biomaRt. They are analogous to what you get when you use the columns method with other objects.

In the biomaRt package, filters are things that can be used with values to restrict or choose what comes back. The ‘values’ here are treated as keys that you are passing in and which you would like to know more information about. In contrast, the filter represents the kind of key that you are searching for. So for example, you might choose a filter name of “chromosome_name” to go with specific value of “1”. Together these two argument values would request whatever attributes matched things on the 1st chromosome. And just as there here is an accessor for attributes, there is also an accessor for filters:

head(listFilters(ensembl))
##              name     description
## 1 chromosome_name Chromosome name
## 2           start Gene Start (bp)
## 3             end   Gene End (bp)
## 4      band_start      Band Start
## 5        band_end        Band End
## 6    marker_start    Marker Start

So now you know about attributes, values and filters, you can call the getBM method to put it all together and request specific data from the mart. So for example, the following requests gene symbols and entrez gene IDs that are found on chromosome 1 of flies:

res <- getBM(attributes=c("hgnc_symbol", "entrezgene"), 
                    filters = "chromosome_name", 
                    values = "1", mart = ensembl)
head(res)
##   hgnc_symbol entrezgene
## 1       MMEL1      79258
## 2              100505887
## 3                     NA
## 4      WRAP73      49856
## 5     CAMK2N1      55450
## 6        FCN3       8547

Of course you may have noticed that a lot of the arguments for getBM are very similar to what you do when you call shsapienselect. So if it’s your preference you can now also use the standard select methods with mart objects.

head(columns(ensembl))
## [1] "3_utr_end"   "3_utr_end"   "3_utr_start" "3_utr_start" "3utr"       
## [6] "5_utr_end"

biomaRt exercises

Exercise 11: Pull down GO terms for entrez gene id “1” from human by using the ensembl “hsapiens_gene_ensembl” dataset.

Exercise 12: Now compare the GO terms you just pulled down to the same GO terms from the org.Hs.eg.db package (which you can now retrieve using select()). What differences do you notice? Why do you suspect that is?

[ Back to top ]

Creating annotation objects

By now you are aware that Bioconductor has a lot of annotation resources. But it is still completely impossible to have every annotation resource pre-packaged for every conceivable use. Because of this, almost all annotation objects have special functions that can be called to create those objects (or the packages that load them) from generalized data resources or specific file types. Below is a table with a few of the more popular options.

If you want this And you have this Then you could call this to help
TxDb tracks from UCSC GenomicFeatures::makeTxDbPackageFromUCSC
TxDb data from biomaRt GenomicFeatures::makeTxDbPackageFromBiomaRt
TxDb gff or gtf file GenomicFeatures::makeTxDbFromGFF
OrgDb custom data.frames AnnotationForge::makeOrgPackage
OrgDb valid Taxonomy ID AnnotationForge::makeOrgPackageFromNCBI
ChipDb org package & data.frame AnnotationForge::makeChipPackage
BSgenome fasta or twobit sequence files BSgenome::forgeBSgenomeDataPkg

In most cases the output for resource creation functions will be an annotation package that you can install.

And there is unfortunately not enough space to demonstrate how to call each of these functions here. But to do so is actually pretty straightforward and most such functions will be well documented with their associated manual pages and vignettes[3,4,10,12]. As usual, you can see the help page for any function right inside of R.

help("makeTxDbPackageFromUCSC")

If you plan to make use of these kinds of functions then you should expect to consult the associated documentation first. These kinds of functions tend to have a lot of arguments and most of them also require that their input data meet some fairly specific criteria. Finally, you should know that even after you have succeeded at creating an annotation package, you will also have to make use of the install.packages() function (with the repos argument=NULL) to install whatever package source directory has just been created.

Important considerations

The bioconductor project represents a very large and active codebase from an active and engaged community. Because of this, you should expect that the software described in this walkthrough will change over time and often in dramatic ways. As an example, the getSeq function that is described in this chapter is expected to a big overhaul in the coming months. When this happens the older function will be deprecated for a full release cycle (6 months) and then labeled as defunct for another release cycle before it is removed. This cycle is in place so that active users can be warned about what is happening and where they should look for the appropriate replacement functionality. But obviously, this system cannot warn end users if they have not been vigilant about updating their software to the latest version. So please take the time to always update your software to the latest version.

To stay abreast of new developments users are encouraged to explore the bioconductor website which contains many current walkthroughs and vignettes. Also visit the support site where you can ask questions and engage in discussions.

sessionInfo()

Package versions used in this tutorial:

sessionInfo()
## R version 3.2.1 (2015-06-18)
## Platform: x86_64-unknown-linux-gnu (64-bit)
## Running under: Ubuntu 14.04.2 LTS
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=C              
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] stats4    parallel  stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] biomaRt_2.25.1                         
##  [2] BSgenome.Hsapiens.UCSC.hg19_1.4.0      
##  [3] BSgenome_1.37.3                        
##  [4] rtracklayer_1.29.12                    
##  [5] Biostrings_2.37.2                      
##  [6] XVector_0.9.1                          
##  [7] Homo.sapiens_1.3.1                     
##  [8] org.Hs.eg.db_3.1.2                     
##  [9] GO.db_3.1.2                            
## [10] RSQLite_1.0.0                          
## [11] DBI_0.3.1                              
## [12] OrganismDbi_1.11.42                    
## [13] TxDb.Hsapiens.UCSC.hg19.knownGene_3.1.3
## [14] GenomicFeatures_1.21.13                
## [15] AnnotationDbi_1.31.17                  
## [16] Biobase_2.29.1                         
## [17] GenomicRanges_1.21.16                  
## [18] GenomeInfoDb_1.5.8                     
## [19] IRanges_2.3.14                         
## [20] S4Vectors_0.7.10                       
## [21] BiocGenerics_0.15.3                    
## [22] AnnotationHub_2.1.30                   
## [23] knitr_1.10.5                           
## [24] BiocStyle_1.7.4                        
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.11.6                  futile.logger_1.4.1         
##  [3] BiocInstaller_1.19.8         formatR_1.2                 
##  [5] futile.options_1.0.0         bitops_1.0-6                
##  [7] tools_3.2.1                  zlibbioc_1.15.0             
##  [9] digest_0.6.8                 evaluate_0.7                
## [11] graph_1.47.2                 shiny_0.12.1                
## [13] curl_0.9.1                   yaml_2.1.13                 
## [15] httr_1.0.0                   stringr_1.0.0               
## [17] R6_2.1.0                     RBGL_1.45.1                 
## [19] BiocParallel_1.3.34          XML_3.98-1.3                
## [21] rmarkdown_0.7                lambda.r_1.1.7              
## [23] magrittr_1.5                 GenomicAlignments_1.5.11    
## [25] Rsamtools_1.21.14            htmltools_0.2.6             
## [27] SummarizedExperiment_0.3.2   mime_0.3                    
## [29] interactiveDisplayBase_1.7.0 xtable_1.7-4                
## [31] httpuv_1.3.2                 stringi_0.5-5               
## [33] RCurl_1.95-4.7

Acknowledgments

Research reported in this chapter was supported by the National Human Genome Research Institute of the National Institutes of Health under Award Number U41HG004059 and by the National Cancer Institute of the National Institutes of Health under Award Number U24CA180996. We also want to thank the numerous institutions who produced and maintained the data that is used for generating and updating the annotation resources described here.

References

  1. Wolfgang Huber, Vincent J Carey, Robert Gentleman, Simon Anders, Marc Carlson, Benilton S Carvalho, Hector Corrada Bravo, Sean Davis, Laurent Gatto, Thomas Girke, Raphael Gottardo, Florian Hahne, Kasper D Hansen, Rafael A Irizarry, Michael Lawrence, Michael I Love, James MacDonald, Valerie Obenchain, Andrzej K Oleś, Hervé Pagès, Alejandro Reyes, Paul Shannon, Gordon K Smyth, Dan Tenenbaum, Levi Waldron & Martin Morgan (2015) Orchestrating high-throughput genomic analysis with Bioconductor Nature Methods 12:115-121

  2. Pages H, Carlson M, Falcon S and Li N. AnnotationDbi: Annotation Database Interface. R package version 1.30.0.

  3. M. Carlson, H. Pages, P. Aboyoun, S. Falcon, M. Morgan, D. Sarkar, M. Lawrence GenomicFeatures: Tools for making and manipulating transcript centric annotations version 1.19.38.

  4. Lawrence M, Huber W, Pagès H, Aboyoun P, Carlson M, Gentleman R, Morgan M and Carey V (2013). Software for Computing and Annotating Genomic Ranges. PLoS Computational Biology, 9. http://dx.doi.org/10.1371/journal.pcbi.1003118, http://www.ploscompbiol.org/article/info%3Adoi%2F10.1371%2Fjournal.pcbi.1003118

  5. Steffen Durinck, Wolfgang Huber biomaRt: Interface to BioMart databases (e.g. Ensembl, COSMIC ,Wormbase and Gramene) version 2.23.5.

  6. Durinck S, Spellman P, Birney E and Huber W (2009). Mapping identifiers for the integration of genomic datasets with the R/Bioconductor package biomaRt. Nature Protocols, 4, pp. 1184-1191.

  7. Durinck S, Moreau Y, Kasprzyk A, Davis S, De Moor B, Brazma A and Huber W (2005). BioMart and Bioconductor: a powerful link between biological databases and microarray data analysis. Bioinformatics, 21, pp. 3439-3440.

  8. Morgan M, Carlson M, Tenenbaum D and Arora S. AnnotationHub: Client to access AnnotationHub resources. R package version 2.0.1.

  9. Carlson M, Pages H, Morgan M and Obenchain V. OrganismDbi: Software to enable the smooth interfacing of different database packages. R package version 1.10.0.

  10. Pages H. BSgenome: Infrastructure for Biostrings-based genome data packages. R package version 1.36.0.

  11. Pages H, Aboyoun P, Gentleman R and DebRoy S. Biostrings: String objects representing biological sequences, and matching algorithms. R package version 2.36.0.

  12. Carlson M, and Pages H. AnnotationForge: Code for Building Annotation Database Packages. R package version 1.10.0.

Answers for exercises

Exercise 1:

The 1st thing you need to do is look for thing from UCSC

ahs <- query(ah, "UCSC")

Then you can look for Genome values that match ‘hg19’ and a species that matches ‘Homo sapiens’.

ahs <- subset(ahs, ahs$genome=='hg19')
length(ahs)
## [1] 5490
ahs <- subset(ahs, ahs$species=='Homo sapiens') 
length(ahs)
## [1] 5490

You might notice that the last two filtering steps are redundant (IOW doing the 1st of them is the same as doing both of them.) If this were not the case, we might suspect that there was a problem with the metadata.

Exercise 2:

This pulls down the oreganno annotations. Which are described on the UCSC site thusly: “This track displays literature-curated regulatory regions, transcription factor binding sites, and regulatory polymorphisms from ORegAnno (Open Regulatory Annotation). For more detailed information on a particular regulatory element, follow the link to ORegAnno from the details page.”

ahs <- query(ah, 'oreganno')
ahs
## AnnotationHub with 9 records
## # snapshotDate(): 2015-05-26 
## # $dataprovider: Pazar, UCSC
## # $species: Homo sapiens, Saccharomyces cerevisiae, NA
## # $rdataclass: GRanges
## # additional mcols(): taxonomyid, genome, description, tags,
## #   sourceurl, sourcetype 
## # retrieve records with, e.g., 'object[["AH5087"]]' 
## 
##             title                                 
##   AH5087  | ORegAnno                              
##   AH5213  | ORegAnno                              
##   AH7053  | ORegAnno                              
##   AH7061  | ORegAnno                              
##   AH22286 | pazar_ORegAnno_20120522.csv           
##   AH22287 | pazar_ORegAnno_ENCODEprom_20120522.csv
##   AH22288 | pazar_ORegAnno_Erythroid_20120522.csv 
##   AH22289 | pazar_ORegAnno_STAT1_ChIP_20120522.csv
##   AH22290 | pazar_ORegAnno_STAT1_lit_20120522.csv
ahs[1]
## AnnotationHub with 1 record
## # snapshotDate(): 2015-05-26 
## # names(): AH5087
## # $dataprovider: UCSC
## # $species: Homo sapiens
## # $rdataclass: GRanges
## # $title: ORegAnno
## # $description: GRanges object from UCSC track 'ORegAnno'
## # $taxonomyid: 9606
## # $genome: hg19
## # $sourcetype: UCSC track
## # $sourceurl: rtracklayer://hgdownload.cse.ucsc.edu/goldenpath/hg19/dat...
## # $sourcelastmodifieddate: NA
## # $sourcesize: NA
## # $tags: oreganno, UCSC, track, Gene, Transcript, Annotation 
## # retrieve record with 'object[["AH5087"]]'
oreg <- ahs[['AH5087']]
oreg
## GRanges object with 23118 ranges and 2 metadata columns:
##                        seqnames           ranges strand   |        name
##                           <Rle>        <IRanges>  <Rle>   | <character>
##       [1]                  chr1 [873499, 873849]      +   | OREG0012989
##       [2]                  chr1 [886764, 887214]      +   | OREG0012990
##       [3]                  chr1 [886938, 886958]      +   | OREG0007909
##       [4]                  chr1 [919400, 919950]      +   | OREG0012991
##       [5]                  chr1 [919695, 919715]      +   | OREG0007910
##       ...                   ...              ...    ... ...         ...
##   [23114]  chr7_gl000195_random [     1,    851]      +   | OREG0026736
##   [23115]  chr7_gl000195_random [103427, 103447]      +   | OREG0012963
##   [23116]  chr7_gl000195_random [121139, 121159]      +   | OREG0012964
##   [23117] chr17_gl000204_random [ 58370,  58955]      +   | OREG0026769
##   [23118] chr17_gl000205_random [117492, 118442]      +   | OREG0026772
##               score
##           <numeric>
##       [1]         0
##       [2]         0
##       [3]         0
##       [4]         0
##       [5]         0
##       ...       ...
##   [23114]         0
##   [23115]         0
##   [23116]         0
##   [23117]         0
##   [23118]         0
##   -------
##   seqinfo: 93 sequences (1 circular) from hg19 genome

Exercise 3:

keys <- "MSX2"
columns <- c("ENTREZID", "CHR")
select(org.Hs.eg.db, keys, columns, keytype="SYMBOL")
## Warning in .deprecatedColsMessage(): Accessing gene location information via 'CHR','CHRLOC','CHRLOCEND'
##   is deprecated. Please use a range based accessor like genes(), or
##   select() with columns values like TXCHROM and TXSTART on a TxDb or
##   OrganismDb object instead.
## 'select()' returned 1:1 mapping between keys and columns
##   SYMBOL ENTREZID CHR
## 1   MSX2     4488   5

Exercise 4:

## 1st get all the gene symbols
orgSymbols <- keys(org.Hs.eg.db, keytype="SYMBOL")
## and then use that to get all gene symbols matched to all entrez gene IDs
egr <- select(org.Hs.eg.db, keys=orgSymbols, "ENTREZID", "SYMBOL")
## 'select()' returned 1:many mapping between keys and columns
length(egr$ENTREZID)
## [1] 56340
length(unique(egr$ENTREZID))
## [1] 56340
## VS:
length(egr$SYMBOL)
## [1] 56340
length(unique(egr$SYMBOL))
## [1] 56332
## So lets trap these symbols that are redundant and look more closely...
redund <- egr$SYMBOL
badSymbols <- redund[duplicated(redund)]
select(org.Hs.eg.db, badSymbols, "ENTREZID", "SYMBOL")
## 'select()' returned 1:many mapping between keys and columns
##       SYMBOL  ENTREZID
## 1        HBD      3045
## 2        HBD 100187828
## 3       RNR1      4549
## 4       RNR1      6052
## 5       RNR2      4550
## 6       RNR2      6053
## 7       SFPQ      6421
## 8       SFPQ    654780
## 9        TEC      7006
## 10       TEC 100124696
## 11     MEMO1      7795
## 12     MEMO1     51072
## 13      MMD2    221938
## 14      MMD2 100505381
## 15 LSAMP-AS1 100506708
## 16 LSAMP-AS1 101926903

Exercise 5:

So to retrieve this information using select you need to do it like this:

res1 <- select(TxDb.Hsapiens.UCSC.hg19.knownGene, 
               keys(TxDb.Hsapiens.UCSC.hg19.knownGene, keytype="TXID"),
               columns=c("GENEID","TXNAME","TXCHROM"), keytype="TXID")
## 'select()' returned 1:1 mapping between keys and columns
head(res1)
##   TXID    GENEID     TXNAME TXCHROM
## 1    1 100287102 uc001aaa.3    chr1
## 2    2 100287102 uc010nxq.1    chr1
## 3    3 100287102 uc010nxr.1    chr1
## 4    4     79501 uc001aal.1    chr1
## 5    5      <NA> uc001aaq.2    chr1
## 6    6      <NA> uc001aar.2    chr1

And to do it using transcripts you do it like this:

res2 <- transcripts(TxDb.Hsapiens.UCSC.hg19.knownGene, 
                    columns = c("gene_id","tx_name")) 
head(res2)
## GRanges object with 6 ranges and 2 metadata columns:
##       seqnames           ranges strand |         gene_id     tx_name
##          <Rle>        <IRanges>  <Rle> | <CharacterList> <character>
##   [1]     chr1 [ 11874,  14409]      + |       100287102  uc001aaa.3
##   [2]     chr1 [ 11874,  14409]      + |       100287102  uc010nxq.1
##   [3]     chr1 [ 11874,  14409]      + |       100287102  uc010nxr.1
##   [4]     chr1 [ 69091,  70008]      + |           79501  uc001aal.1
##   [5]     chr1 [321084, 321115]      + |                  uc001aaq.2
##   [6]     chr1 [321146, 321207]      + |                  uc001aar.2
##   -------
##   seqinfo: 92 sequences (1 circular) from hg19 genome

Notice that in the 2nd case we don’t have to ask for the chromosome, as transcripts() returns a GRanges object, so the chromosome will automatically be returned as part of the object.

Exercise 6:

library(TxDb.Athaliana.BioMart.plantsmart22)
res <- transcripts(TxDb.Athaliana.BioMart.plantsmart22, columns = c("gene_id")) 

You will notice that the gene ids for this package are TAIR locus IDs and are NOT entrez gene IDs like what you saw in the TxDb.Hsapiens.UCSC.hg19.knownGene package. It’s important to always pay attention to the kind of gene id is being used by the TxDb you are looking at.

Exercise 7:

library(Homo.sapiens)
keys <- keys(Homo.sapiens, keytype="TXID")
res1 <- select(Homo.sapiens, 
               keys= keys,
               columns=c("SYMBOL","TXSTART","TXCHROM"), keytype="TXID")

head(res1)

And to do it using transcripts you do it like this:

library(Homo.sapiens)
res2 <- transcripts(Homo.sapiens, columns="SYMBOL") 
## 'select()' returned 1:1 mapping between keys and columns
head(res2)
## GRanges object with 6 ranges and 1 metadata column:
##       seqnames           ranges strand |          SYMBOL
##          <Rle>        <IRanges>  <Rle> | <CharacterList>
##   [1]     chr1 [ 11874,  14409]      + |         DDX11L1
##   [2]     chr1 [ 11874,  14409]      + |         DDX11L1
##   [3]     chr1 [ 11874,  14409]      + |         DDX11L1
##   [4]     chr1 [ 69091,  70008]      + |           OR4F5
##   [5]     chr1 [321084, 321115]      + |              NA
##   [6]     chr1 [321146, 321207]      + |              NA
##   -------
##   seqinfo: 92 sequences (1 circular) from hg19 genome

Exercise 8:

columns(Homo.sapiens)
##  [1] "ACCNUM"       "ALIAS"        "CDSCHROM"     "CDSEND"      
##  [5] "CDSID"        "CDSNAME"      "CDSSTART"     "CDSSTRAND"   
##  [9] "DEFINITION"   "ENSEMBL"      "ENSEMBLPROT"  "ENSEMBLTRANS"
## [13] "ENTREZID"     "ENZYME"       "EVIDENCE"     "EVIDENCEALL" 
## [17] "EXONCHROM"    "EXONEND"      "EXONID"       "EXONNAME"    
## [21] "EXONRANK"     "EXONSTART"    "EXONSTRAND"   "GENEID"      
## [25] "GENENAME"     "GO"           "GOALL"        "GOID"        
## [29] "IPI"          "MAP"          "OMIM"         "ONTOLOGY"    
## [33] "ONTOLOGYALL"  "PATH"         "PFAM"         "PMID"        
## [37] "PROSITE"      "REFSEQ"       "SYMBOL"       "TERM"        
## [41] "TXCHROM"      "TXEND"        "TXID"         "TXNAME"      
## [45] "TXSTART"      "TXSTRAND"     "TXTYPE"       "UCSCKG"      
## [49] "UNIGENE"      "UNIPROT"
columns(org.Hs.eg.db)
##  [1] "ACCNUM"       "ALIAS"        "ENSEMBL"      "ENSEMBLPROT" 
##  [5] "ENSEMBLTRANS" "ENTREZID"     "ENZYME"       "EVIDENCE"    
##  [9] "EVIDENCEALL"  "GENENAME"     "GO"           "GOALL"       
## [13] "IPI"          "MAP"          "OMIM"         "ONTOLOGY"    
## [17] "ONTOLOGYALL"  "PATH"         "PFAM"         "PMID"        
## [21] "PROSITE"      "REFSEQ"       "SYMBOL"       "UCSCKG"      
## [25] "UNIGENE"      "UNIPROT"
columns(TxDb.Hsapiens.UCSC.hg19.knownGene)
##  [1] "CDSCHROM"   "CDSEND"     "CDSID"      "CDSNAME"    "CDSSTART"  
##  [6] "CDSSTRAND"  "EXONCHROM"  "EXONEND"    "EXONID"     "EXONNAME"  
## [11] "EXONRANK"   "EXONSTART"  "EXONSTRAND" "GENEID"     "TXCHROM"   
## [16] "TXEND"      "TXID"       "TXNAME"     "TXSTART"    "TXSTRAND"  
## [21] "TXTYPE"
## You might also want to look at this:
transcripts(Homo.sapiens, columns=c("SYMBOL","CHRLOC"))
## 'select()' returned 1:1 mapping between keys and columns
## GRanges object with 82508 ranges and 1 metadata column:
##           seqnames                 ranges strand   |          SYMBOL
##              <Rle>              <IRanges>  <Rle>   | <CharacterList>
##       [1]     chr1       [ 11874,  14409]      +   |         DDX11L1
##       [2]     chr1       [ 11874,  14409]      +   |         DDX11L1
##       [3]     chr1       [ 11874,  14409]      +   |         DDX11L1
##       [4]     chr1       [ 69091,  70008]      +   |           OR4F5
##       [5]     chr1       [321084, 321115]      +   |              NA
##       ...      ...                    ...    ... ...             ...
##   [82504]     chrX [154686575, 154688276]      -   |            F8A1
##   [82505]     chrX [154689080, 154689596]      -   |          H2AFB3
##   [82506]     chrX [154718673, 154842622]      -   |           TMLHE
##   [82507]     chrX [154722196, 154842622]      -   |           TMLHE
##   [82508]     chrX [155255323, 155257848]      -   |              NA
##   -------
##   seqinfo: 92 sequences (1 circular) from hg19 genome

The key difference is that the TXSTART refers to the start of a transcript and originates in the TxDb object from the TxDb.Hsapiens.UCSC.hg19.knownGene package, while the CHRLOC refers to the same thing but originates in the OrgDb object from the org.Hs.eg.db package. The point of origin is significant because the TxDb object represents a transcriptome from UCSC and the OrgDb is primarily gene centric data that originates at NCBI. The upshot is that CHRLOC will not have as many regions represented as TXSTART, since there has to be an official gene for there to even be a record. The CHRLOC data is also locked in for org.Hs.eg.db as data for hg19, whereas you can swap in a different TxDb object to match the genome you are using to make it hg18 etc. For these reasons, we strongly recommend using TXSTART instead of CHRLOC. Howeverm CHRLOC still remains in the org packages for historical reasons.

Exercise 9

To find the keys that match, make use of the pattern and column arguments.

library(Homo.sapiens)
xk = head(keys(Homo.sapiens, keytype="ENTREZID", pattern="X", column="SYMBOL"))
xk
## [1] "51"  "179" "189" "239" "240" "241"

select verifies the results

select(Homo.sapiens, xk, "SYMBOL", "ENTREZID")
## 'select()' returned 1:1 mapping between keys and columns
##   ENTREZID  SYMBOL
## 1       51   ACOX1
## 2      179   AGMX2
## 3      189    AGXT
## 4      239  ALOX12
## 5      240   ALOX5
## 6      241 ALOX5AP

Exercise 10:

library("BSgenome.Hsapiens.UCSC.hg19")
## Get the transcript ranges grouped by gene
txby <- transcriptsBy(Homo.sapiens, by="gene")
## look up the entrez ID for the gene symbol 'PTEN'
select(Homo.sapiens, keys='PTEN', columns='ENTREZID', keytype='SYMBOL')
## 'select()' returned 1:1 mapping between keys and columns
##   SYMBOL ENTREZID
## 1   PTEN     5728
## subset that genes transcripts
geneOfInterest <- txby[["5728"]]
## extract the sequence
res <- getSeq(Hsapiens, geneOfInterest)
res
##   A DNAStringSet instance of length 2
##      width seq
## [1] 105338 CCTCCCCTCGCCCGGCGCGGTCCCGTCCGCC...TTAAAACTGATTAAAGTCTCATTCTTGTCA
## [2] 105338 CCTCCCCTCGCCCGGCGCGGTCCCGTCCGCC...TTAAAACTGATTAAAGTCTCATTCTTGTCA

Exercise 11:

library("biomaRt")
ensembl <- useMart("ensembl",dataset="hsapiens_gene_ensembl")
ids=c("1")
getBM(attributes=c('go_id', 'entrezgene'), 
            filters = 'entrezgene',
                    values = ids, mart = ensembl)
##        go_id entrezgene
## 1 GO:0005575          1
## 2 GO:0005576          1
## 3 GO:0043226          1
## 4 GO:0008150          1
## 5 GO:0005615          1
## 6 GO:0003674          1
## 7 GO:0070062          1
## 8 GO:0072562          1
## 9 GO:0005515          1

Exercise 12:

library(org.Hs.eg.db)
ids=c("1")
select(org.Hs.eg.db, keys=ids, columns="GO", keytype="ENTREZID")
## 'select()' returned 1:many mapping between keys and columns
##   ENTREZID         GO EVIDENCE ONTOLOGY
## 1        1 GO:0003674       ND       MF
## 2        1 GO:0005576      IDA       CC
## 3        1 GO:0005615      IDA       CC
## 4        1 GO:0008150       ND       BP
## 5        1 GO:0070062      IDA       CC
## 6        1 GO:0072562      IDA       CC

When this exercise was written, there was a different number of GO terms returned from biomaRt than from org.Hs.eg.db. This may not always be true in the future though as both of these resources are updated. It is expected however that this web service, (which is updated continuously) will fall in and out of sync with the org.Hs.eg.db package (which is updated twice a year). This is an important difference as each approach has different advantages and disadvantages. The advantage to updating continuously is that you always have the very latest annotations which are frequently different for something like GO terms. The advantage to using a package is that the results are frozen to a release of Bioconductor. And this can help you to get the same answers that you get today (reproducibility), a few years from now.

[ Back to top ]