Count Table Anatomy

Workshop 2, Module 2



Wi-Fi

Network: Golden_Tulip

Click on Conference

Password: Diamond254

Yesterday you built a count table out of pom-poms

Today the same table has 220 rows of bacteria, 14,226 rows of human genes, and 471 columns.

Reading the files

library(tidyverse)
library(here)

data_dir <- "data/2-workshop2/instructional_dataset"

metadata <- read_csv(here(data_dir, "01_metadata.csv"))
species  <- read_csv(here(data_dir, "02_microbiome_counts.csv"))
genes    <- read_csv(here(data_dir, "04_rnaseq_counts.csv.gz"))

Three of the six files in the folder. Each one becomes a tibble.

The six files

file what it holds
01_metadata.csv one row per sample: participant, visit, outcome, clinical measures
02_microbiome_counts.csv 220 bacterial species x 471 samples
03_microbiome_taxonomy.csv what each species is: domain down to species
04_rnaseq_counts.csv.gz 14,226 human genes x 471 samples
05_gene_annotation.csv what each gene is: Ensembl id, symbol, name
06_cytokines.csv measured protein concentrations, for the group projects

A corner of the species table

feature P001_week_18 P001_week_24 P001_week_34
lactobacillus_iners 2956 2301 7528
lactobacillus_crispatus 30 45 30
gardnerella_swidsinskii_leopoldii 193 17977 10336
lactobacillus_jensenii 18362 9 0
candidatus_lachnocurva_vaginae_bvab1 0 6 9
gardnerella_vaginalis 46 3961 4184

6 of 220 rows and 3 of 471 columns: participant P001 at three visits.

A corner of the gene table

feature P001_week_18 P001_week_24 P001_week_34
ENSG00000188976 275 432 705
ENSG00000187961 20 8 33
ENSG00000187583 63 17 109
ENSG00000187642 0 0 24
ENSG00000188290 62 39 44
ENSG00000187608 132 71 70

The same three samples. Both tables have features in rows, samples in columns and counts in the cells.

One row per count

species_long <- species |>
  pivot_longer(-taxon,
               names_to = "sample_id", values_to = "count")
taxon sample_id count
lactobacillus_iners P001_week_18 2956
lactobacillus_iners P001_week_24 2301
lactobacillus_iners P001_week_34 7528
lactobacillus_crispatus P001_week_18 30
lactobacillus_crispatus P001_week_24 45
lactobacillus_crispatus P001_week_34 30

220 species times 471 samples gives 103,620 rows.

In this shape, group_by(sample_id) works on one sample at a time and group_by(taxon) works on one species at a time.

The questions we ask of both tables

  1. How deeply was each sample sequenced?
  2. How many features did we see in each sample?
  3. How evenly is each sample spread across its features?
  4. Which features can we afford to keep?

Answering them is the quality control step, and it is all we do today.

1. Sequencing depth

table median smallest largest
species 28,703 438 155,686
genes 12,220,381 6,026,167 28,835,256

Both spread over more than an order of magnitude. Note the axis labels.

One sample has 438 bacterial reads. What would you do with it?

2. Features detected

Deeper gene libraries do detect more genes (rho = 0.50), but only about 110 more from the shallowest fifth of samples to the deepest, out of 14,226.

In the species table depth barely matters at these depths (rho = 0.06). The community does: samples dominated by Lactobacillus show a median of 17.5 species, and the rest show 33.

The same picture as a fraction

table features in the table median detected median share detected median cells that are zero
species 220 24 10.9% 89.1%
genes 14,226 14,084 99.0% 1.0%

The species table is mostly zeros and the gene table is almost solid, so the two tables need different filters.

3. Dominance by one feature

Half of our bacterial samples are more than 60% one species. The most extreme is 99.9%.

Same number of colours, different diversity

Which bag is more diverse? Counting colours says they are nearly the same.

Shannon diversity is the average surprise

Draw one ball. If its colour makes up a share p of the bag, your surprise is −ln(p).

  • an orange from bag 1, 84% of it: 0.17
  • a blue from bag 1, 2% of it: 3.91
  • Shannon is the average over many draws: −Σ p ln(p)
  • Rare colours surprise you a lot, but you rarely draw them, so they add little.
bag colours top colour Shannon
bag 1 6 84% 0.66
bag 2 6 76% 0.90
bag 3 7 70% 1.12
bag 4 7 46% 1.56
one colour only 1 100% 0.00
8 colours, 6 of each 8 12% 2.08

The effective number of species

exp(Shannon) is how many equally common colours would give the same Shannon value.

bag colours effective number
bag 1 6 1.9
bag 2 6 2.5
bag 3 7 3.1
bag 4 7 4.8
one colour only 1 1.0
8 colours, 6 of each 8 8.0

Bag 1 has six colours but behaves like two. Bag 4 behaves like five.

Computing it for every sample

species_long |>
  group_by(sample_id) |>
  mutate(p = count / sum(count)) |>
  filter(p > 0) |>
  summarise(shannon   = -sum(p * log(p)),
            effective = exp(shannon))

log() in R is the natural log, and exp() undoes it.

Start from genes_long and the same six lines give the numbers for the gene table.

Our two tables, as effective numbers

The median vaginal sample behaves like 3 equally common species. The median transcriptome behaves like about 1,000 equally expressed genes.

In the vagina, low diversity is the healthy state

Samples dominated by Lactobacillus behave like about 2 species. The rest behave like about 9. In the gut, more diverse usually reads as healthier. Here it is the reverse.

What Shannon diversity tracks in our tables

Spearman correlations
Shannon against species genes
library size 0.03 0.06
features detected 0.76 0.35
top feature’s share -0.97 -0.93

Depth barely moves it, because depth mostly changes how many rare features you catch, and rare features add little. In both tables it is close to the mirror image of dominance, the share held by the top feature.

Shannon diversity of a transcriptome

Nobody reports the Shannon diversity of a transcriptome, even though “behaves like about a thousand equally expressed genes” is a fair summary of one.

Still, the number of features you detected and how evenly the counts are spread are what you look at to decide which samples to throw away, in both experiments.

Microbiome papers report these numbers as alpha diversity. RNA-seq papers bury them in the QC section.

Quick check

4. Filtering features

# keep a species if it appears in at least 10% of samples
species_kept <- species_long |>
  group_by(taxon) |>
  filter(mean(count > 0) >= 0.10) |>
  ungroup()

The filter curve at four cutoffs

prevalence cutoff species: features kept species: counts kept genes: features kept genes: counts kept
0% 220 100.00% 14,226 100.00%
10% 59 99.24% 14,226 100.00%
25% 32 95.79% 14,225 100.00%
50% 18 90.62% 14,220 100.00%
  • Species: a 10% prevalence filter drops 161 of 220 features and loses 0.8% of the data.
  • Genes: the same filter drops nothing, so prevalence is the wrong thing to filter on.

A different filter for each table

sparse table (species) dense table (genes)
the problem most features are absent from most samples nearly everything is present at some level
filter on prevalence expression level
typical rule present in at least 10% of samples mean CPM of at least 5
what it buys you fewer tests, less noise fewer tests, less noise

You cannot compare raw counts

species_long |>
  group_by(sample_id) |>
  mutate(proportion = count / sum(count),
         cpm        = proportion * 1e6) |>
  ungroup()

Microbiome papers call this “relative abundance”. RNA-seq papers call it “CPM”.

And then you take a log

The + 1 is there because log2(0) is negative infinity. That choice changes your answer, and you should be able to say why you made it.

One helper for both tables

as_counts() builds the same kind of object from either table, and we use it all week.

library(microViz)
source("R/count_tables.R")

species_ps <- as_counts(table = "microbiome")
genes_ps   <- as_counts(table = "rnaseq")

microViz was written for microbiome data. It wants a count table, a sample table, and a table saying what each feature is. A gene annotation fills that third slot, so the same verbs work on genes.

microViz wants species genes
counts 02_microbiome_counts.csv 04_rnaseq_counts.csv.gz
samples 01_metadata.csv 01_metadata.csv
what each feature is 03_microbiome_taxonomy.csv: Domain down to species 05_gene_annotation.csv: locus_group, then symbol

The same call, twice

species_ps |>
  comp_barplot(tax_level = "Genus", n_taxa = 10)

genes_ps |>
  comp_barplot(tax_level = "symbol", n_taxa = 10)

The first is the stacked bar chart from almost every microbiome paper you have read.

Nobody makes the second. The next two slides show why.

Ten genera fill the bar

Stacked bar chart of the ten most abundant genera in 471 samples. Lactobacillus fills most bars and the grey Other block is barely visible.

In a typical sample the ten largest genera hold 99% of the reads.

Ten genes leave most of the bar grey

Stacked bar chart of the ten most abundant genes in 471 samples. The grey Other block takes up most of every bar.

In a typical sample the ten largest genes hold 26% of the reads. The grey block is the other 14,216 genes.

A heatmap gives each feature its own row

A stacked bar has to share one axis between all the features, so anything below a few percent disappears.

In a heatmap each feature gets a row and each sample a column. The colour of a cell is that feature’s share of that sample, on a log scale.

species_log <- species_ps |>
  tax_transform("compositional", rank = "Genus") |>
  tax_transform("log2", zero_replace = "halfmin",
                chain = TRUE)

species_log |>
  comp_heatmap(taxa = tax_top(species_log, n = 20))

Twenty genera in 471 samples

Heatmap of the 20 most abundant genera across 471 samples, with a strip on top coloured by community group.

Darker cells are larger shares. comp_heatmap() puts similar samples next to each other. The strip on top is the grouping column you build in Exercise 2.

The same heatmap for genes

genes_log <- genes_ps |>
  tax_transform("compositional", rank = "symbol") |>
  tax_transform("log2", zero_replace = "halfmin",
                chain = TRUE)

genes_log |>
  comp_heatmap(taxa = tax_top(genes_log, n = 25))

The code changes in two places: the rank is "symbol", and we ask for 25 rows.

Twenty-five genes in 471 samples

Heatmap of the 25 most abundant genes across 471 samples, with a strip on top coloured by community group.

HBA1, HBA2 and HBB are haemoglobin, and they rise and fall together. What does a sample that is dark in those three rows have in it?

Bar chart or heatmap?

stacked bar chart heatmap
shows shares that add up to the whole sample each feature on its own row
scale linear log
suits a few features that hold most of the counts many features, large and small
species table yes yes
gene table no yes

Quick check

Where you write code this week

A Codespace is a computer that GitHub runs for you. R, Quarto, the packages and the data are already on it.

VS Code is the editor you see in the browser tab. Your files are on the left, the open notebook is in the middle, and the terminal is at the bottom.

Nothing is installed on your laptop.

A Codespace in the browser: file explorer on the left, a document in the middle, and a terminal at the bottom with Pi starting.

A chat window and an agent

With a chat window you copy code into R, run it, and copy the error back. An agent has tools for those steps and repeats them until it thinks the task is done.

One request, many steps

You type: plot the library size of every sample in the species table

  1. Pi reads notebooks/02-count-table-anatomy.qmd
  2. It reads the first lines of 02_microbiome_counts.csv
  3. It writes a chunk that reshapes the table and draws a histogram
  4. It runs the chunk and gets an error about a column name
  5. It fixes the chunk and runs it again
  6. It tells you what it did

Pi does not stop to ask you between steps. Read the code from step 5 before you believe the summary in step 6.

Pi works from what is in your folder

Before it answers, Pi reads CLAUDE.md at the top of your repository. Ours says you are a biologist who is new to coding.

After that it knows only the files it opens and the conversation so far.

  • An old notebook with a different filter looks as valid to Pi as today’s.
  • Two csv files with similar names get mixed up.
  • A long conversation about one question bends its answers to the next.

Type /new to start a fresh conversation when you change task.

Pi, Claude Code and Codex

All three are coding agents that run in a terminal and work in the same loop.

Pi Claude Code Codex
made by an open-source project Anthropic OpenAI
models from any provider built for Claude built for GPT
you pay through our OpenRouter key, per request an Anthropic plan or API key an OpenAI plan or API key
before running a command does not ask asks, unless you change it asks, unless you change it

We chose Pi because one key reaches models from many companies, so you can change model with one command and see what each costs. What you practise with Pi carries over to the other two.

Models cost different amounts

Your key has a $3 daily limit. Every request spends some of it.

  • Pi starts on z-ai/glm-5.3-flash, which is cheap and fast.
  • /model or Ctrl+L switches to z-ai/glm-5.3, the larger model from the same family. It costs more per request.
  • Start on the cheap one. Switch when it gets stuck, and switch back after.

A long conversation costs more per message than a short one, because the whole conversation is sent with every request.

Pi in a Codespace

Open your Codespace, open a terminal, type pi and press Enter.

Follow along while we give Pi its first task.

What changes when code is cheap

Code is cheap now. Cognitive load is more expensive, because we can do more than we used to. It is still your job, as a scientist or a statistician, to understand the choices you made and be able to defend them.

So you spend less time coding and more time reviewing. Ask for lots of plots. Ask for reports. Argue with the computer.

You can get to the first polished-looking output very fast, but in some ways that is when your job begins now.

Plan for the next ninety minutes

  1. Ask Pi for library size, features detected and diversity in both tables, and check them
  2. Look at the same numbers several ways and decide which samples to drop
  3. Polish one figure, one request at a time
  4. Compare several filters side by side and pick one you can defend
  5. Build the one column the rest of the week depends on
  6. Draw both tables as bar charts and heatmaps, and ask for variations

Do not skip step 5. This afternoon you colour your ordinations by that column, and Wednesday afternoon starts from it.

Your turn

Open notebooks/02-count-table-anatomy.qmd in your Codespace.