LSMA

LONDON SCHOOL OF MULTIOMICS & AI

LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 31 lessons

Matrices, lists and factors

Matrices, lists and factors

Matrices, lists and factors

A count matrix, a test result and a sample sheet each rest on one of three structures. This lesson works with all three on the airway data and shows the silent mistakes each one invites.

This lesson follows Data frames and files, which introduced matrices, lists and factors in a few lines each. Here you use them on a real count matrix.

Matrices: the shape of omics data

Almost every omics dataset arrives as a matrix: one row per feature (a gene, a protein, a CpG site) and one column per sample. The airway experiment you met in Data frames and files is stored this way inside the airway package. Install it once with install.packages("BiocManager") and then BiocManager::install(c("airway", "SummarizedExperiment")). Its count matrix is the real thing: tens of thousands of genes, eight samples.

R
library(airway)
library(SummarizedExperiment)
data("airway")
counts <- assay(airway)
class(counts)
dim(counts)
counts[1:3, 1:4]

What this does

  • data("airway") loads the dataset, an object that bundles the counts with the sample sheet. assay(airway) takes out the count matrix, stored as counts.
  • class() says what kind of object it is, and dim() gives rows, then columns.
  • counts[1:3, 1:4] prints a corner: the first three genes in the first four samples. Never print the whole thing.
[1] "matrix" "array" [1] 63677 8 SRR1039508 SRR1039509 SRR1039512 SRR1039513 ENSG00000000003 679 448 873 408 ENSG00000000005 0 0 0 0 ENSG00000000419 467 515 621 365

Reading the output. 63,677 rows (genes, named by Ensembl IDs) and 8 columns (samples, named by run IDs). The names are the matrix's dimnames: rownames(counts) and colnames(counts) return them, and they travel with every subset you take. That is what keeps a count attached to the right gene and sample. The second gene has no reads at all, which is common: many genes are not expressed in a given tissue.

Summaries along rows and columns

Questions about a matrix are usually asked along one direction: per gene (across rows) or per sample (down columns). rowSums(), rowMeans(), colSums() and colMeans() are fast built-in versions. For anything else, apply(x, 1, f) applies a function f to every row, and apply(x, 2, f) to every column. The 1 and 2 are the same "which dimension" codes that sweep() used in Data frames and files.

R
keep <- rowSums(counts >= 10) >= 4
cpm  <- sweep(counts[keep, ], 2, colSums(counts[keep, ]), "/") * 1e6
logc <- log2(cpm + 1)
dim(logc)
gene_sd <- apply(logc, 1, sd)
summary(rowMeans(logc))
top <- names(sort(gene_sd, decreasing = TRUE))[1:5]
round(logc[top, ], 1)
dim(t(logc))

What this does, line by line

  1. counts >= 10 gives a matrix of TRUE and FALSE of the same shape. rowSums() counts the TRUEs per gene, and keep marks genes with at least 10 reads in at least 4 samples.
  2. The sweep() line divides each column by its own total and multiplies by a million: counts per million (CPM), which removes differences in sequencing depth.
  3. log2(cpm + 1) works on every value at once. The +1 avoids taking the log of zero.
  4. apply(logc, 1, sd) computes the SD of each row, one per gene.
  5. sort(…, decreasing = TRUE) puts the most variable genes first, and names(…)[1:5] keeps the first five gene IDs.
  6. t() transposes: rows become columns. Many functions, such as dist() and prcomp(), expect samples in rows, so you will often write t(logc).
[1] 16139 8 Min. 1st Qu. Median Mean 3rd Qu. Max. 0.3511 1.9461 3.8968 3.8883 5.4742 13.8494 SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 ENSG00000129824 7.9 7.8 7.5 7.4 7.7 ENSG00000067048 6.2 6.0 5.8 5.9 6.2 ENSG00000114374 6.1 6.0 6.0 5.9 6.0 ENSG00000012817 5.8 5.7 5.7 5.4 5.9 ENSG00000109906 0.3 5.3 0.3 4.9 0.1 SRR1039517 SRR1039520 SRR1039521 ENSG00000129824 7.5 0.0 0.1 ENSG00000067048 6.3 0.0 0.1 ENSG00000114374 6.0 0.1 0.0 ENSG00000012817 5.6 0.1 0.1 ENSG00000109906 4.3 0.7 5.7 [1] 8 16139

Reading the output. 16,139 genes pass the filter. The five most variable genes tell a story. The first four are high in six samples and essentially zero in SRR1039520 and SRR1039521, the two samples from donor N061011. These are RPS4Y1, DDX3Y, USP9Y and KDM5D, genes on the Y chromosome, so that donor's cells are almost certainly from a female and the other three from males. The fifth, ZBTB16, is low in every untreated sample and high in every treated one: a strong dexamethasone response. One apply() call surfaced both the biggest biological signal and a hidden donor variable. The last line confirms t() turned 16,139 × 8 into 8 × 16,139.

z-scores with scale()

To compare the pattern of genes whose levels differ, as a heatmap does, you put each gene on a common scale. A z-score is a value minus its mean, divided by its SD: it says how many SDs a sample sits above or below that gene's average. scale() does this, but for each column. Genes are rows, so you transpose, scale, and transpose back.

R
z <- t(scale(t(logc[top, ])))
round(z, 1)
round(rowMeans(z), 10)
apply(z, 1, sd)
SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 ENSG00000129824 0.6 0.6 0.5 0.5 0.6 ENSG00000067048 0.6 0.5 0.4 0.5 0.6 ENSG00000114374 0.6 0.5 0.5 0.5 0.5 ENSG00000012817 0.6 0.6 0.5 0.4 0.6 ENSG00000109906 -0.9 1.0 -0.9 0.8 -1.0 … attr(,"scaled:center") ENSG00000129824 ENSG00000067048 ENSG00000114374 ENSG00000012817 ENSG00000109906 5.740556 4.567973 4.513509 4.264995 2.693019 … ENSG00000129824 ENSG00000067048 ENSG00000114374 ENSG00000012817 ENSG00000109906 0 0 0 0 0 ENSG00000129824 ENSG00000067048 ENSG00000114374 ENSG00000012817 ENSG00000109906 1 1 1 1 1

Reading the output. Each gene now has mean 0 and SD 1, as the last two lines confirm. scale() also stores the means and SDs it used as attributes, scaled:center and scaled:scale. The ZBTB16 row now alternates between about −1 and +1, untreated and treated, on the same scale as the Y genes. Without the double t(), scale() would have standardised each sample instead, a different and usually meaningless operation, with no error to warn you.

Worked example · one z-score by hand

RPS4Y1: mean 5.74, SD 3.51 (log2 CPM)
SRR1039508: 7.9 → (7.9 − 5.74) ÷ 3.51 = +0.6
SRR1039520: 0.0 → (0.0 − 5.74) ÷ 3.51 = −1.6

Step by step. The mean is the scaled:center value, 5.74, and the SD, 3.51, is scaled:scale. For the first sample, 7.9 − 5.74 = 2.16, and 2.16 ÷ 3.51 = 0.62, printed as 0.6. For the female donor's sample, 0 − 5.74 = −5.74, and −5.74 ÷ 3.51 = −1.64, printed as −1.6.

What the answer means. A z-score keeps the pattern and discards the level. That is right for a heatmap of patterns, but it hides that this gene is far more abundant than ZBTB16, and it makes a nearly flat gene look as dramatic as a strongly changing one. Choose the genes on their real scale first, then scale them for display.

Matrix arithmetic

Arithmetic signs work element by element: with m <- matrix(1:6, nrow = 2), m * m squares each of the six values (1, 4, 9, 16, 25, 36). True matrix multiplication is a different operator, %*%: each result is a row of the first matrix multiplied pairwise with a column of the second and summed. m %*% t(m) gives a 2 × 2 matrix whose first value is 1×1 + 3×3 + 5×5 = 35. You rarely write %*% yourself, but it is how models are computed, as Linear models with groups and covariates shows. Some functions return a whole matrix: cor(logc) gives the 8 × 8 matrix of correlations between samples, here 0.97 to 0.98 for the first three.

Lists: how R bundles results

A list holds items of any type and length. Two ways of indexing it matter, and they are easy to confuse. Single brackets, x["a"], return a smaller list containing item a. Double brackets, x[["a"]], or x$a, return the item itself. Think of a list as a train: [ ] gives you a carriage, [[ ]] the contents of the carriage.

R
expt <- list(name = "airway", n_samples = ncol(counts),
             donors = unique(as.character(airway$cell)),
             libsize = colSums(counts))
str(expt)
expt["donors"]
expt[["donors"]]
class(expt["donors"]); class(expt[["donors"]])
names(expt)
List of 4 $ name : chr "airway" $ n_samples: int 8 $ donors : chr [1:4] "N61311" "N052611" "N080611" "N061011" $ libsize : Named num [1:8] 20637971 18809481 25348649 15163415 24448408 ... ..- attr(*, "names")= chr [1:8] "SRR1039508" "SRR1039509" "SRR1039512" "SRR1039513" ... $donors [1] "N61311" "N052611" "N080611" "N061011" [1] "N61311" "N052611" "N080611" "N061011" [1] "list" [1] "character" [1] "name" "n_samples" "donors" "libsize"

Reading the output. str() is the best way to look inside a list: one line per item, with its type, length and first values. The two prints of donors look almost alike, but the first starts with $donors, the sign that it is still a list, and class() confirms the difference. Functions that expect a vector, such as length() of the donors or paste(), give surprising answers when handed a one-item list instead.

Results are lists

Most results in R are lists with a class attached. A test result is one, a model is one, and the DESeq2 objects of Module 4 are built on the same idea. Once you know that, names() and $ let you take out exactly the number you need instead of copying it from the printout. Here is a t-test, the subject of Comparing two groups, on one gene:

R
coldata <- as.data.frame(colData(airway))
treated <- coldata$dex == "trt"
gene    <- "ENSG00000152583"
tt <- t.test(logc[gene, treated], logc[gene, !treated])
class(tt)
names(tt)
tt$p.value
tt[["conf.int"]]
[1] "htest" [1] "statistic" "parameter" "p.value" "conf.int" "estimate" [6] "null.value" "stderr" "alternative" "method" "data.name" [1] 1.910671e-05 [1] 3.638737 4.722645 attr(,"conf.level") [1] 0.95

Reading the output. The result has class htest (hypothesis test), but underneath it is a list of ten named items. tt$p.value and tt[["conf.int"]] pull out two of them: treated samples sit 3.6 to 4.7 log2 units higher for this gene, SPARCL1. Extracting values this way is what lets you run a test on thousands of genes and collect the answers.

Applying a function to every item

lapply() runs a function on each item of a list and returns a list; sapply() does the same and simplifies the answer to a vector when it can. Both appeared briefly in Vectors, functions and loops. They come into their own with split(), which cuts a vector into a list of groups.

R
by_donor <- split(rownames(coldata), coldata$cell)
str(by_donor)
lfc <- sapply(by_donor, function(s) {
  trt   <- s[coldata[s, "dex"] == "trt"]
  untrt <- s[coldata[s, "dex"] == "untrt"]
  unname(logc[gene, trt] - logc[gene, untrt])
})
round(lfc, 2)
List of 4 $ N052611: chr [1:2] "SRR1039512" "SRR1039513" $ N061011: chr [1:2] "SRR1039520" "SRR1039521" $ N080611: chr [1:2] "SRR1039516" "SRR1039517" $ N61311 : chr [1:2] "SRR1039508" "SRR1039509" N052611 N061011 N080611 N61311 4.00 4.31 3.64 4.77

Reading the output. split() made a list with one item per donor, each holding that donor's two sample names. sapply() then ran a small unnamed function on each: find the treated and untreated sample, and subtract. The result is one log2 fold change per donor, all close to 4, a 16-fold rise in every donor. This is the paired comparison of Comparing two groups, done by hand. unname() drops the sample name from each difference, so the result is labelled by donor alone.

Factors in depth

A factor stores each value as a whole number, a code, plus a table of levels that says what each code means. Two arguments of factor() are easy to mix up. levels says which values exist and in what order. labels says what to call them, in that same order.

R
dose_code <- c(0, 1, 1, 0, 2, 1)
dose <- factor(dose_code, levels = c(0, 1, 2), labels = c("none", "low", "high"))
dose
as.integer(dose)
table(dose)

wrong <- factor(c("trt", "untrt", "trt"), labels = c("untrt", "trt"))
wrong
[1] none low low none high low Levels: none low high [1] 1 2 2 1 3 2 dose none low high 2 3 1 [1] untrt trt untrt Levels: untrt trt

Reading the output. The codes 0, 1 and 2 became the labels none, low and high, in that order, and as.integer() shows the codes R stores underneath, 1 to 3. The second example is a silent disaster. Without levels, R sorts the text alphabetically, so the levels are "trt", "untrt". The labels then rename them in that order: every "trt" became "untrt" and the reverse. To set the order, use levels; use labels only to rename codes you have listed.

Order sets comparisons

The first level is the reference. Models compare every other level with it, and plots, tables and legends follow the level order. Look at how airway ships:

R
grp <- factor(c("untrt", "untrt", "trt", "trt"))
levels(grp)
y <- c(5, 6, 9, 10)
coef(lm(y ~ grp))
grp2 <- relevel(grp, ref = "untrt")
coef(lm(y ~ grp2))
levels(coldata$dex)
[1] "trt" "untrt" (Intercept) grpuntrt 9.5 -4.0 (Intercept) grp2trt 5.5 4.0 [1] "trt" "untrt"

Reading the output. With alphabetical levels, "trt" is the reference, so the model reports untreated as 4 lower than treated (the intercept, 9.5, is the treated mean). After relevel(), the same data give treated as 4 higher than untreated. The numbers are identical; only the direction of the comparison changed. The last line shows that the real airway sample sheet also has "trt" first, which is why RNA-seq counts and exploration relevels it before any analysis.

Two more traps

Levels outlive their data. Filter out the only "high" dose and table() still lists high with a count of 0; droplevels() removes it. Do this after filtering, or empty groups appear in plots and models complain about levels with no data.

The worst trap concerns numbers stored as factors, which happens when a column of doses or concentrations is read as text. conc <- factor(c("10", "5", "20", "5")) has levels "10", "20", "5" (text sorts by first character). as.numeric(conc) returns the codes, 1 3 2 3, not the values. as.numeric(as.character(conc)) returns 10 5 20 5, as intended. The wrong version gives plausible small numbers and no warning.

Common mistakes

  • Running scale() on a genes-by-samples matrix and standardising samples instead of genes. Transpose first.
  • Using [ ] on a list when you wanted the item. Use [[ ]] or $.
  • Reordering a factor with labels, which renames instead. Use levels or relevel().
  • Calling as.numeric() on a factor of numbers. Go through as.character() first.
  • Selecting columns by position after a filter that changed their order. Select by name; the dimnames are there to be used.

The airway data are from Himes et al. 2014 (PLOS ONE), a study of glucocorticoid response in airway smooth muscle cells. Cite it, and the package with citation("airway"), when you use the data. The gene symbols in this lesson come from the Bioconductor annotation package org.Hs.eg.db, which Volcano plot and interpretation uses to label genes. Genes such as RPS4Y1, DDX3Y and KDM5D lie on the Y chromosome and are widely used to check the recorded sex of samples, because a mislabelled or swapped sample often shows up there first. The sex of the airway donors is not recorded in the sample sheet; the inference above comes from the counts alone.

Further reading · Module 1R for Data Science, 2nd edition: the free book that covers this module and much more. · All reading for this course

Check your understanding

1. Your matrix logc has genes in rows and samples in columns. How do you turn each gene into z-scores?

2. expt is a list with an item called donors. What does expt["donors"] return?

3. conc <- factor(c("10", "5", "20")). What does as.numeric(conc) return?

Ask LSMA