LSMA

LONDON SCHOOL OF MULTIOMICS & AI

LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 31 lessons

Importing Salmon and kallisto counts

Importing Salmon and kallisto counts

Importing Salmon and kallisto counts

Salmon and kallisto count reads per transcript, not per gene. This lesson sums them to genes with tximport, keeps the length information, and hands the result to DESeq2.

This lesson follows RNA-seq counts and exploration, where the airway count matrix arrived ready-made inside a Bioconductor package. With your own data, you have to build that matrix from the files a quantification tool writes. This lesson shows how.

Where count matrices come from

A sequencer produces millions of short reads, fragments of RNA sequence, for each sample. Turning them into a table of genes and samples needs two decisions: where did each read come from, and how should reads be added up per gene? There are two main routes.

  • Alignment, then counting. An aligner such as HISAT2 or STAR finds the position of each read in the genome. A counting tool such as featureCounts then counts the reads that overlap each gene. The result is a whole-number count per gene, like the airway counts. Reads that overlap two genes are usually left out.
  • Pseudo-alignment or quasi-mapping. Salmon and kallisto skip the full alignment. For each read they work out only which transcripts (the different RNA versions a gene can make, also called isoforms) it is compatible with. A statistical model then shares out reads that fit several transcripts, in proportion to how abundant each transcript appears to be. This is much faster than alignment and uses the reads that would otherwise be discarded.

The second route has two consequences that matter in R. First, its estimates are per transcript, not per gene, so they must be added up to genes. Second, a read shared between transcripts contributes a fraction to each, so the "counts" are estimated counts with decimals. They are still on the scale of reads, which is what DESeq2 needs; they are not TPM.

TPM, transcripts per million, is the other number these tools report. It divides each transcript's reads by its length and then scales the sample to a total of one million. TPM is useful for comparing genes within a sample, but it has thrown away how many reads lie behind each value, which is exactly what the count model needs. The tool that bridges the gap is tximport.

Reading Salmon output with tximport

The tximportData package contains real Salmon and kallisto output for six samples of human lymphoblastoid cell lines from the GEUVADIS project. Salmon writes one folder per sample, holding a file called quant.sf (here compressed as quant.sf.gz).

R · run once
BiocManager::install(c("tximport", "tximportData"))
install.packages("readr")
R
library(tximport)
library(readr)
library(DESeq2)

dir     <- system.file("extdata", package = "tximportData")
samples <- read.table(file.path(dir, "samples.txt"), header = TRUE)

files <- file.path(dir, "salmon", samples$run, "quant.sf.gz")
names(files) <- samples$run
all(file.exists(files))

q <- read_tsv(files[1], show_col_types = FALSE)
head(q, 3)

tx2gene <- read_csv(file.path(dir, "tx2gene.gencode.v27.csv"),
                    show_col_types = FALSE)
head(tx2gene, 3)

What this does

  • system.file("extdata", package = "tximportData") finds the example folder inside the installed package.
  • samples.txt is the sample sheet. Its run column holds the run accession of each sample, which is also the name of that sample's Salmon folder.
  • file.path() builds one path per sample, and names(files) <- samples$run labels each path. tximport uses these names as the column names of the matrices it returns, so name them carefully.
  • all(file.exists(files)) checks that every file is where you think it is. A typing error in one path otherwise surfaces only as a confusing error later.
  • read_tsv(), from readr, opens one quant.sf file to look at it. tx2gene is a two-column table linking each transcript ID to its gene ID, from the same GENCODE release (version 27) that Salmon was run against.
[1] TRUE # A tibble: 3 × 5 Name Length EffectiveLength TPM NumReads <chr> <dbl> <dbl> <dbl> <dbl> 1 ENST00000456328.2 1657 1459. 0.0591 1.73 2 ENST00000450305.2 632 434. 0 0 3 ENST00000488147.1 1351 1095. 5.46 120. # A tibble: 3 × 2 TXNAME GENEID <chr> <chr> 1 ENST00000456328.2 ENSG00000223972.5 2 ENST00000450305.2 ENSG00000223972.5 3 ENST00000473358.1 ENSG00000243485.5

Each quant.sf has 200,401 rows, one per transcript. Length is the transcript's length in bases. EffectiveLength is shorter: the number of positions a sequenced fragment could actually start from, adjusted by Salmon for fragment size and biases. NumReads is the estimated count, with decimals, and TPM is the abundance. The IDs carry version suffixes, such as .2, and so does tx2gene; the two must match exactly.

R
txi <- tximport(files, type = "salmon", tx2gene = tx2gene)
names(txi)
dim(txi$counts)
txi$counts[1:3, 1:3]
[1] "abundance" "counts" "length" [4] "countsFromAbundance" [1] 58288 6 ERR188297 ERR188088 ERR188329 ENSG00000000003.14 2.58012 2.000 27.09648 ENSG00000000005.5 0.00000 0.000 0.00000 ENSG00000000419.12 1056.99960 1337.997 1452.99497

tximport() reads all six files and sums transcripts to genes using tx2gene: 200,401 transcripts become 58,288 genes. It returns a list of three matrices with the same shape. counts holds the estimated counts per gene, the sum of NumReads over each gene's transcripts. abundance holds TPM per gene. length holds an average transcript length per gene and sample, explained next. The fourth element, countsFromAbundance, records how the counts were made; here it is "no", meaning they are the original estimated counts.

Worked example · a gene's average transcript length

A gene with two transcripts: A is 1,000 bases long with TPM 30, B is 2,000 bases with TPM 10. The gene's length in this sample is the average of the transcript lengths, weighted by how abundant each one is:

(1,000 × 30 + 2,000 × 10) ÷ (30 + 10)
= (30,000 + 20,000) ÷ 40 = 1,250 bases
GAPDH, sample ERR188297, 10 expressed transcripts: 1,028.3 bases
GAPDH across the six samples: 977.5 to 1,071.2 bases

Step by step. Multiply each transcript's effective length by its TPM, add the products, and divide by the total TPM. Because A is three times as abundant, the average sits closer to its length. For GAPDH, doing the same sum by hand over its 10 expressed transcripts in quant.sf gives 1,028.28, the value in txi$length.

What the answer means. If a treatment shifted a gene towards a longer transcript, the gene would collect more reads at the same number of RNA molecules, and its count would rise with no real change in expression. Because the average length is recorded per sample, the model can correct for that.

kallisto works the same way

kallisto writes a folder per sample with abundance.tsv (or the faster abundance.h5). In tximportData its transcript names are long strings joined by vertical bars, starting ENST00000456328.2|ENSG00000223972.5|…, so tximport is told to keep only the part before the first bar.

R
files_k <- file.path(dir, "kallisto", samples$run, "abundance.tsv.gz")
names(files_k) <- samples$run
txi_k <- tximport(files_k, type = "kallisto", tx2gene = tx2gene,
                  ignoreAfterBar = TRUE)
dim(txi_k$counts)

common <- intersect(rownames(txi$counts), rownames(txi_k$counts))
cor(log2(txi$counts[common, 1] + 1), log2(txi_k$counts[common, 1] + 1))
Note: importing `abundance.h5` is typically faster than `abundance.tsv` … [1] 58288 6 [1] 0.9987624

The same 58,288 genes come out, and for the first sample the gene counts from the two tools correlate at 0.999 on a log scale. Their total counts per sample differ by under 0.1%. The two tools use different models but agree closely at gene level; choose one for a study and use it for every sample.

Into DESeq2

DESeqDataSetFromTximport() replaces DESeqDataSetFromMatrix(). It rounds the estimated counts to whole numbers and, importantly, keeps the average transcript lengths.

R
coldata <- data.frame(row.names = samples$run, pop = samples$pop)
all(rownames(coldata) == colnames(txi$counts))

dds <- DESeqDataSetFromTximport(txi, colData = coldata, design = ~ 1)
dds
dds <- estimateSizeFactors(dds)
sizeFactors(dds)
dim(normalizationFactors(dds))
[1] TRUE using counts and average transcript lengths from tximport class: DESeqDataSet dim: 58288 6 metadata(1): version assays(2): counts avgTxLength … using 'avgTxLength' from assays(dds), correcting for library size NULL [1] 58288 6

What this does

  • coldata is the sample sheet, with run accessions as row names in the same order as the columns of txi$counts. The all() check is the same as for airway.
  • design = ~ 1 means "no groups": these six samples all come from one population and one centre, so there is nothing to compare. With your own data you would write ~ condition, or ~ batch + condition as the next lesson explains. The design can also be changed later with design(dds) <-.
  • The printed object shows two assays: counts, now whole numbers, and avgTxLength, the matrix from txi$length.
  • estimateSizeFactors() sees the lengths and computes normalisation factors instead: one number per gene and sample, combining sequencing depth with gene length in that sample. That is why sizeFactors(dds) prints NULL and normalizationFactors(dds) is a full 58,288 × 6 matrix. DESeq() does this step for you.

Statisticians call this kind of per-gene, per-sample correction an offset: a known quantity built into each gene's model so that the expected count reflects depth and length, while the counts themselves stay untouched. It is the right way to use transcript-level information in a gene-level test.

The countsFromAbundance option

Not every tool accepts an offset. For those, tximport can instead build counts that already include the length correction: tximport(..., countsFromAbundance = "lengthScaledTPM") turns the TPM values back into counts, scaled by the average length across all samples and by each sample's library size. In this data, each sample's total stays the same (22,830,167 reads for ERR188297 either way), but individual genes move: GAPDH in ERR188088 goes from 241,378.7 to 246,971.7. A third option, "scaledTPM", ignores length altogether. For DESeq2, the original counts with the offset are the usual choice; the scaled counts are for tools that take a plain count matrix.

Go deeper: staying at transcript level

Summing to genes answers "is this gene's total output changing?". Sometimes the question is about the transcripts themselves: does a treatment switch a gene from one isoform to another, with little change in its total? tximport(files, type = "salmon", txOut = TRUE) skips the summing and returns all 200,401 transcripts.

Transcript-level testing is harder. Many reads fit several transcripts, so each transcript's estimate is less certain than a gene's, and Salmon can measure that uncertainty with repeated estimates (the salmon_gibbs and kallisto_boot folders in tximportData hold examples). Dedicated methods such as DEXSeq, DRIMSeq and fishpond use that information. Start at gene level, and move to transcripts only when the question needs it.

Common mistakes

  • Mismatched transcript IDs. If tx2gene has no version suffixes and the quant files do (or the reverse), tximport stops with an error that none of the transcripts are in tx2gene. Use a tx2gene from the same annotation release you quantified against, or use ignoreTxVersion = TRUE.
  • Forgetting the bars. kallisto run on a GENCODE transcript file keeps the long names with vertical bars; ignoreAfterBar = TRUE fixes it.
  • Giving TPM to DESeq2. TPM has lost the read numbers. Use DESeqDataSetFromTximport() on the whole txi list.
  • Rounding counts yourself and calling DESeqDataSetFromMatrix(). It runs, but the average lengths are thrown away.
  • Unnamed files. Without names(files), the columns have no sample names and the order check against the sample sheet cannot be done.

tximport and the length offset are described in Soneson, Love & Robinson 2015, "Differential analyses for RNA-seq: transcript-level estimates improve gene-level inferences" (F1000Research). Salmon is from Patro et al. 2017 (Nature Methods) and kallisto from Bray et al. 2016 (Nature Biotechnology); featureCounts, for the alignment route, from Liao, Smyth & Shi 2014 (Bioinformatics). The example samples are from the GEUVADIS project, Lappalainen et al. 2013 (Nature). Report the quantification tool and its version, the transcript annotation and its release (here GENCODE 27), and the tximport version.

Key point

Salmon and kallisto estimate reads per transcript. tximport sums them to genes and keeps each gene's average transcript length, and DESeqDataSetFromTximport() passes both to DESeq2. Everything after that, from filtering to DESeq(), is the same as for airway.

Before the test, though, comes a question every real dataset raises: were the samples processed in batches? Batch effects and design formulas shows how to see that and how to write it into the design.

Further reading · Module 4Love, Huber & Anders 2014: the method, and why it shrinks fold changes. · All reading for this course

Check your understanding

1. Why are Salmon's estimated counts not whole numbers?

2. What does DESeqDataSetFromTximport() keep that rounding the counts and using DESeqDataSetFromMatrix() would lose?

3. tximport stops, saying none of the transcripts are in tx2gene. What is the most likely cause?

Ask LSMA