Skip to contents

This vignette walks through a complete antibiotic resistance gene workflow with sra2lab: setting up an analysis directory, the conda environments and CARD’s reference data, listing the SRA runs of a BioProject, mapping them to CARD with rgi_runs(), and combining and inspecting the results in R.

The example BioProject is PRJNA1556220, “Microbiome changes in the peri-heart transplant setting”: 67 paired-end Illumina shotgun metagenomes from skin (axilla and groin) and gut (perirectal and stool) swabs. The same 8 runs are profiled in vignette("sylph-workflow", package = "sra2lab") and vignette("funprofiler-workflow", package = "sra2lab"), so the results can be compared.

The Resistance Gene Identifier (RGI) finds antibiotic resistance genes using the Comprehensive Antibiotic Resistance Database (CARD). Its read-mapping command, rgi bwt, aligns a metagenome’s reads to CARD’s reference sequences and reports how many reads map to each resistance gene. rgi_runs() downloads each SRA run in turn, maps it, and deletes the reads before moving on, so only one run’s reads are on disk at a time.

Read-level results only. rgi_runs() gives read-level results: rgi bwt aligns each read to CARD with KMA, a k-mer-based aligner, and counts the reads that map to each gene. It does not assemble reads into contigs or run rgi main, the contig-based analysis that applies RGI’s Perfect/Strict/Loose criteria and that pipelines such as CZ ID’s combine with read mapping. See Read-level and contig-level results below before interpreting the results.

Before you start

You need:

  • conda, for example Miniconda. sra2lab looks for ~/miniconda3/bin/conda by default; see ?conda_bin if yours is elsewhere.
  • CARD’s reference data, downloaded from CARD and loaded with RGI (step 3). This is essential: RGI ships without it, and rgi_runs() stops before downloading any reads if it can’t find it. This vignette uses CARD 4.0.2. The loaded data and its indexes take about 80 MB.
  • Internet access to NCBI and CARD, and enough disk space in the analysis directory for one run’s download, its reads and the temporary files fasterq-dump writes while extracting them, and RGI’s outputs (step 5).

1. Set up an analysis directory

Keep each analysis in its own directory. sra2lab’s functions write to paths relative to the working directory: run metadata and results go under data/, and environment specifications under methods/. RGI always looks for its data in a directory called localDB, and by default rgi_runs() uses the one above the working directory, so a layout like this keeps one copy of CARD’s data for many analyses:

~/projects/
├── localDB/                        <- CARD data, loaded by RGI (step 3, shared)
└── PRJNA1556220/                   <- analysis directory (working directory)
    ├── data/
    │   ├── PRJNA1556220_runs.csv   <- run metadata (step 4)
    │   └── rgi/                    <- RGI's results for each run (step 5)
    └── methods/
        └── rgi_env.yml             <- environment specification (step 2)

Create the analysis directory and make it the working directory (or create an RStudio project there, which does the same):

library(sra2lab)

analysis_dir <- "~/projects/PRJNA1556220"
dir.create(analysis_dir, recursive = TRUE, showWarnings = FALSE)
setwd(analysis_dir)

2. Set up and document the conda environments

rgi_runs() uses two environments: sra_env (the SRA Toolkit, to download reads, and EDirect, to query NCBI) and rgi_env (RGI, with the KMA, Bowtie2 and BWA aligners and the Jellyfish k-mer counter it needs). Each only needs to be created once per computer:

setup_conda_sra(yes = TRUE)
setup_conda_rgi(yes = TRUE)

If an environment already exists, these calls stop with an error and leave it untouched (use overwrite = TRUE to rebuild it).

Then record the exact environment used for this analysis, with every package’s version and build:

document_conda_sra(write_yml = TRUE)
document_conda_rgi(write_yml = TRUE)
#> Wrote methods/rgi_env.yml
#> name: rgi_env
#> channels:
#>   - conda-forge
#>   - bioconda
#>   - defaults
#> dependencies:
#>   ...
#>   - bowtie2=2.5.5=hd99aea0_2
#>   - bwa=0.7.19=hba9b596_1
#>   ...
#>   - kma=1.7.1=h6bd33b9_0
#>   ...
#>   - rgi=6.0.8=pyh05cac1d_0
#> ...

Keeping these files with the analysis lets you report the tool versions and recreate the environment later with conda env create -f methods/rgi_env.yml.

3. Download and load the CARD database (essential)

Don’t skip this step. RGI is installed without any reference data, so before rgi_runs() can map anything you need to download CARD’s data and load it with RGI. It only needs doing once per computer (and again whenever you want a newer CARD release), in the directory above your analysis directories, where rgi_runs() looks for it by default.

In a terminal:

cd ~/projects                              # the directory above the analysis

# 1. download the latest CARD data and extract card.json
wget https://card.mcmaster.ca/latest/data
tar -xvf data ./card.json

# 2. make RGI's reference sequences from it
conda run -n rgi_env rgi card_annotation -i card.json

# 3. load them into ./localDB
conda run -n rgi_env rgi load -i card.json --local \
  --card_annotation card_database_v4.0.2.fasta \
  --card_annotation_all_models card_database_v4.0.2_all.fasta

rgi card_annotation names its files after the CARD version (here 4.0.2), so check the names it writes and use them in rgi load. --local puts the data in a localDB directory in the current directory; RGI only ever looks for a directory with that name. Afterwards, localDB should hold card.json, card_reference.fasta and card_reference_all.fasta, among others (about 80 MB). RGI builds its alignment indexes inside it the first time it maps reads.

Then record which CARD release you used, with your methods and alongside methods/rgi_env.yml, since results depend on the CARD version as well as the RGI version:

cd ~/projects
conda run -n rgi_env rgi database --version --local
#> 4.0.2

If localDB is missing, or isn’t where card_db points, rgi_runs() stops straight away, before downloading anything:

rgi_runs(to_map)
#> Error: CARD database not found: ../localDB. Load CARD with `rgi load --local` (see ?rgi_runs).

It also checks that localDB has the data the chosen options need. The --card_annotation_all_models file is only needed for include_other_models = TRUE (step 5), and CARD’s Resistomes & Variants data, for include_wildcard = TRUE, is a separate download; see RGI’s rgi bwt documentation.

4. List the SRA runs in the BioProject

get_bioproject_runs() queries NCBI for every run in the BioProject and returns one row per run (SRR ID), with its sequencing details and the BioSample metadata the submitters provided:

runs <- get_bioproject_runs("PRJNA1556220")
#> Querying NCBI SRA for PRJNA1556220 ...

dir.create("data", showWarnings = FALSE)
write.csv(runs, "data/PRJNA1556220_runs.csv", row.names = FALSE)

The run table from that query is saved as data/PRJNA1556220_runs.csv, so it can be read back in later steps (or sessions) without querying NCBI again:

runs <- read.csv("data/PRJNA1556220_runs.csv")
dim(runs)
#> [1] 67 31
table(runs$isolation_source, runs$organism)
#>                  
#>                   human gut metagenome human skin metagenome
#>   Axilla Swab                        0                     5
#>   Groin Swab                         0                    15
#>   Perirectal Swab                   24                     0
#>   Stool Swab                        23                     0
summary(runs$size / 1e9)  # run sizes, GB
#>    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#>  0.3779  0.5793  0.9983  0.9239  1.1129  1.9082

All 67 runs are paired-end shotgun metagenomes (library_strategy WGS), from 18 subjects (host_subject_id). The whole BioProject is about 62 GB of reads. For this example, pick the two smallest runs of each swab type:

runs <- runs[order(runs$size), ]
to_map <- do.call(rbind, lapply(split(runs, runs$isolation_source), head, 2))
rownames(to_map) <- NULL
to_map[, c("run_accession", "isolation_source", "host_subject_id", "size")]
#>   run_accession isolation_source host_subject_id       size
#> 1   SRR41520897      Axilla Swab         GOL_015  569543795
#> 2   SRR41520919      Axilla Swab         GOL_016 1036597186
#> 3   SRR41520874       Groin Swab         GOL_034  560547549
#> 4   SRR41520873       Groin Swab         GOL_017  571965183
#> 5   SRR41520878  Perirectal Swab         GOL_017  377877890
#> 6   SRR41520882  Perirectal Swab         GOL_017  551256914
#> 7   SRR41520894       Stool Swab         GOL_018  489008698
#> 8   SRR41520884       Stool Swab         GOL_003  493557313

To map the whole BioProject instead, pass runs itself (or any filtered version of it) to rgi_runs().

5. Map the runs to CARD with RGI

rgi_runs() takes the run table (it needs only the run_accession column) and, for each run, downloads the run with prefetch, extracts its reads with fasterq-dump, maps them to CARD with rgi bwt, and writes RGI’s results to data/rgi/:

res <- rgi_runs(to_map, card_db = "../localDB", threads = 6, quiet = TRUE)
#> [1/8] SRR41520897: downloading (prefetch) ...
#> [1/8] SRR41520897: extracting and compressing reads (fasterq-dump) ...
#> [1/8] SRR41520897: mapping reads to CARD (kma) ...
#> [1/8] SRR41520897: wrote data/rgi/SRR41520897_kma.gene_mapping_data.txt
#> [2/8] SRR41520919: downloading (prefetch) ...
#> [2/8] SRR41520919: extracting and compressing reads (fasterq-dump) ...
#> ...
#> [8/8] SRR41520884: wrote data/rgi/SRR41520884_kma.gene_mapping_data.txt
#> Done: 8 mapped, 0 skipped, 0 failed.

res[, c("run_accession", "gene_mapping", "status", "message")]
#> # A tibble: 8 × 4
#>   run_accession gene_mapping                                   status message
#>   <chr>         <chr>                                          <chr>  <chr>
#> 1 SRR41520897   data/rgi/SRR41520897_kma.gene_mapping_data.txt mapped <NA>
#> 2 SRR41520919   data/rgi/SRR41520919_kma.gene_mapping_data.txt mapped <NA>
#> ...
#> 8 SRR41520884   data/rgi/SRR41520884_kma.gene_mapping_data.txt mapped <NA>

The result also records the options each output was made with (aligner, include_wildcard and include_other_models). These 8 runs (about 4.7 GB) took just under two hours, mostly downloading. Download speed depends on your connection and on NCBI.

quiet = TRUE hides the tools’ own progress output, including fasterq-dump’s, which keeps the console readable on a long job. It also hides the first sign of a slow or failing download: a large run can show nothing after “downloading (prefetch) …” or “extracting and compressing reads (fasterq-dump) …” for many minutes. For a first run, or on an unreliable connection, leave quiet at its default (FALSE). Either way, a run that fails is reported straight away, with a line such as [2/8] SRR41520919: FAILED: fasterq-dump failed (exit status N). ...; the reason is kept in the result’s message column, and running the same call again retries only the failed runs.

For each run, rgi bwt writes several files, named <SRR>_<aligner>.<output>:

File Contents
gene_mapping_data.txt reads mapped to each resistance gene: the main result
allele_mapping_data.txt, allele_mapping_data.json the same, for each allele (reference sequence) of each gene
overall_mapping_stats.txt total and mapped reads
reference_mapping_stats.txt, artifacts_mapping_stats.txt other mapping statistics

The allele-level JSON file can be large (up to about 220 MB per run here), so delete it if you don’t need it. The read alignments (BAM) are deleted unless keep_bam = TRUE.

The main options are those of rgi bwt:

  • aligner: "kma" (the default, and RGI’s recommendation), "bowtie2" or "bwa". Several aligners give one set of outputs each.
  • include_wildcard: also map to CARD’s Resistomes & Variants sequences, resistance gene variants found in sequenced genomes. Outputs get a _wildcard suffix.
  • include_other_models: also map to CARD’s protein variant, rRNA variant, knockout and overexpression models. Outputs get an _other_models suffix. RGI doesn’t yet check these hits for the mutations that confer resistance, so treat them with care.

RGI’s Perfect/Strict/Loose criteria, the nudge of Loose hits to Strict, and the sequence quality setting (offered by CARD’s RGI web portal) belong to rgi main, which analyses assembled contigs or proteins, so they don’t apply to rgi bwt or to rgi_runs().

As with the other *_runs() functions:

  • Restarting. Runs whose results already exist are skipped, so an interrupted job can be restarted with the same call (overwrite = TRUE maps them again).
  • Failures. A run that fails to download or map is reported with a warning and marked "failed" in the result, with the reason in message; the other runs still go ahead.
  • Storage. Only one run’s reads are on disk at a time, as working_data.fastq.gz, which is deleted at the end. Use working_file = "working_data.fastq" to skip compressing the reads, which is faster if there is disk space for several times as much. On WSL2, keep the analysis directory in the Linux file system (under ~), not on a Windows drive under /mnt/, which is much slower.

6. Combine the results

Each gene mapping file is a tab-separated table with one row per CARD gene (ARO term) that at least one read mapped to. Read them all into one table, taking each run’s accession from the file name. The column names contain spaces and symbols, so keep them as they are with check.names = FALSE:

gene_files <- list.files(file.path("data", "rgi"),
                         pattern = "_kma[.]gene_mapping_data[.]txt$",
                         full.names = TRUE)
length(gene_files)
#> [1] 8

read_genes <- function(file) {
  genes <- read.delim(file, check.names = FALSE)
  genes$run_accession <- sub("_kma[.].*$", "", basename(file))
  genes
}
genes <- do.call(rbind, lapply(gene_files, read_genes))
dim(genes)
#> [1] 766  27

The main columns are:

Column Meaning
ARO Term, ARO Accession the resistance gene, as named in CARD’s Antibiotic Resistance Ontology
AMR Gene Family, Drug Class, Resistance Mechanism CARD’s classification of the gene (several values are separated by "; ")
All Mapped Reads reads mapped to the gene
Completely Mapped Reads reads mapped along their whole length
Average Percent Coverage share of the gene’s length covered by reads (%), averaged over its alleles
Average MAPQ (Completely Mapped Reads) average mapping quality
Reference Length length of the gene’s reference sequence (bp)

rgi bwt reports raw read counts, which depend on sequencing depth and gene length, so they can’t be compared directly between samples or genes. A common normalisation is reads per kilobase of gene per million reads (RPKM). Each run’s total read count is in its overall_mapping_stats.txt:

stats_files <- list.files(file.path("data", "rgi"),
                          pattern = "_kma[.]overall_mapping_stats[.]txt$",
                          full.names = TRUE)
read_count <- function(file, label) {
  line <- grep(paste0("^", label, ":"), readLines(file), value = TRUE)
  as.numeric(sub(paste0("^", label, ":\\s+([0-9]+).*$"), "\\1", line))
}
stats <- data.frame(
  run_accession = sub("_kma[.].*$", "", basename(stats_files)),
  total_reads = vapply(stats_files, read_count, numeric(1),
                       label = "Total reads"),
  mapped_reads = vapply(stats_files, read_count, numeric(1),
                        label = "Mapped reads"),
  row.names = NULL
)
stats$percent_mapped <- round(100 * stats$mapped_reads / stats$total_reads, 3)
stats
#>   run_accession total_reads mapped_reads percent_mapped
#> 1   SRR41520873    12741930       972846          7.635
#> 2   SRR41520874    12698830      1129212          8.892
#> 3   SRR41520878     7241566        20808          0.287
#> 4   SRR41520882    11976553        49270          0.411
#> 5   SRR41520884    11287077         3517          0.031
#> 6   SRR41520894    10765452         3236          0.030
#> 7   SRR41520897    12883126       131535          1.021
#> 8   SRR41520919    24319182       339261          1.395

Both reads of each pair count toward the total. Under 10% of each run’s reads map to CARD (as few as 0.03% in the stool swabs), as expected: most reads come from genes that have nothing to do with resistance, or from the human host.

Add the totals and the run metadata, and compute RPKM for each gene:

genes <- merge(genes, stats[, c("run_accession", "total_reads")],
               by = "run_accession")
genes <- merge(genes,
               to_map[, c("run_accession", "isolation_source",
                          "host_subject_id")],
               by = "run_accession")
genes$rpkm <- genes[["All Mapped Reads"]] /
  (genes[["Reference Length"]] / 1e3) / (genes$total_reads / 1e6)

7. Filter and inspect the results

Many genes have reads mapped to only a small part of their length, often from short stretches they share with other genes. A gene that is really present should be covered along most of its length, so keep only genes with at least 50% average coverage (a common choice; stricter analyses also require a minimum number of reads or mapping quality):

summary(genes[["Average Percent Coverage"]])
#>    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#>    1.12   13.54   42.69   51.33   99.70  100.00
detected <- genes[genes[["Average Percent Coverage"]] >= 50, ]
c(all = nrow(genes), detected = nrow(detected))
#>      all detected 
#>      766      352

How many resistance genes were detected in each sample, and how abundant were they overall?

per_sample <- aggregate(cbind(genes_detected = 1, total_rpkm = rpkm) ~
                          run_accession + isolation_source,
                        data = detected, FUN = sum)
per_sample$total_rpkm <- round(per_sample$total_rpkm)
per_sample[order(per_sample$isolation_source), ]
#>   run_accession isolation_source genes_detected total_rpkm
#> 1   SRR41520897      Axilla Swab             26       7988
#> 2   SRR41520919      Axilla Swab             23      14801
#> 3   SRR41520873       Groin Swab             35     105823
#> 4   SRR41520874       Groin Swab             41     117934
#> 5   SRR41520878  Perirectal Swab             76       1945
#> 6   SRR41520882  Perirectal Swab             82       2823
#> 7   SRR41520884       Stool Swab             16         42
#> 8   SRR41520894       Stool Swab             53        277

The perirectal swabs have the most resistance genes (76 and 82), but the skin swabs have by far the most resistance gene reads: 8,000 to 118,000 RPKM, against under 3,000 in the gut swabs. The two stool swabs have the fewest of both.

Which genes are they? The most abundant genes differ between swab types, so take the six most abundant genes of each swab type and make a genes × runs matrix of their RPKM, with runs ordered by swab type:

site_top <- function(d) {
  names(sort(tapply(d$rpkm, d[["ARO Term"]], sum), decreasing = TRUE))[1:6]
}
top_genes <- unique(unlist(lapply(split(detected, detected$isolation_source),
                                  site_top)))
sample_order <- to_map$run_accession[order(to_map$isolation_source)]
rpkm <- xtabs(rpkm ~ `ARO Term` + run_accession, data = detected)
rpkm <- rpkm[top_genes, sample_order]

# shorter labels for the plot
gene_labels <- sub(" conferring resistance to .*$", "", rownames(rpkm))
gene_labels <- sub(" chloramphenicol acetyltransferase$", " cat",
                   gene_labels)
gene_labels
#>  [1] "ErmC"                           "Staphylococcus intermedius cat"
#>  [3] "qacA"                           "ANT(4')-Ia"                    
#>  [5] "Staphylococcus aureus mupA"     "dfrC"                          
#>  [7] "Enterococcus faecalis cat"      "gadX"                          
#>  [9] "CRP"                            "AcrS"                          
#> [11] "TolC"                           "H-NS"                          
#> [13] "gadW"                           "APH(3')-IIa"                   
#> [15] "TEM-116"                        "BLMT"                          
#> [17] "tet(A)"                         "ErmB"                          
#> [19] "BRP(MBL)"

And plot it as a heatmap of log10 RPKM, with genes not detected in a sample left blank:

site <- to_map$isolation_source[match(sample_order, to_map$run_accession)]
log_rpkm <- log10(unclass(rpkm))
log_rpkm[!is.finite(log_rpkm)] <- NA
breaks <- -1:6
cols <- hcl.colors(length(breaks) - 1, "YlOrRd", rev = TRUE)

op <- par(mar = c(7, 13, 1, 7), xpd = FALSE)
image(seq_len(ncol(log_rpkm)), seq_len(nrow(log_rpkm)),
      t(log_rpkm[nrow(log_rpkm):1, ]), breaks = breaks, col = cols,
      axes = FALSE, xlab = "", ylab = "")
abline(v = c(2.5, 4.5, 6.5), col = "grey60", lwd = 1)
axis(1, at = seq_len(ncol(log_rpkm)), labels = colnames(log_rpkm), las = 2,
     cex.axis = 0.75, tick = FALSE)
axis(2, at = seq_len(nrow(log_rpkm)), labels = rev(gene_labels), las = 1,
     cex.axis = 0.75, tick = FALSE, font = 3)
mtext(sort(unique(site)), side = 1, line = 5.5,
      at = tapply(seq_along(site), site, mean), cex = 0.75, font = 2)
legend(par("usr")[2] + 0.2, par("usr")[4], xpd = TRUE, bty = "n",
       cex = 0.75, title = "log10 RPKM",
       legend = rev(paste(head(breaks, -1), "to", breaks[-1])),
       fill = rev(cols), border = NA)

Heatmap of log10 RPKM for the six most abundant resistance genes of each swab type in the eight runs, grouped by swab type.

par(op)

The skin swabs share a set of staphylococcal resistance genes, at high abundance: ermC (macrolides), qacA (antiseptics), ANT(4’)-Ia (aminoglycosides), mupA (mupirocin), dfrC (trimethoprim) and a chloramphenicol acetyltransferase. ermC alone has over 100,000 RPKM in one groin swab. These swabs also carry mecA (methicillin resistance) and the beta-lactamase blaZ (see rpkm for other genes). This fits the sylph profiles, in which these swabs are dominated by Staphylococcus epidermidis.

The perirectal swabs’ most abundant genes are Escherichia coli efflux pump genes and their regulators (gadX, CRP, AcrS, TolC, H-NS, gadW), matching the sylph profiles in which E. coli is the most abundant genome. The stool swabs have the fewest resistance gene reads. Their most abundant genes, mostly from one swab (SRR41520894), include APH(3’)-IIa (aminoglycosides), the beta-lactamase TEM-116 and the bleomycin resistance gene BLMT, along with tet(A) (tetracyclines) and ermB (macrolides), which is also found in three skin and both perirectal swabs.

Some cautions when reading such results:

  • Similar genes. Reads from closely related genes can map to several CARD references: the Staphylococcus intermedius and Enterococcus faecalis chloramphenicol acetyltransferase genes, which appear together here, are probably one gene.
  • Intrinsic genes. Many genes in CARD, such as E. coli’s efflux pumps and regulators, are in every genome of a species and confer resistance only when mutated or overexpressed, so their presence alone says little about resistance.
  • Contamination. Some genes, such as APH(3’)-IIa, TEM-116 and the bleomycin resistance genes, are common in laboratory cloning vectors and reagents, so at low abundance they may come from contamination rather than the sample. Negative controls help to tell.

Drug classes can be summarised the same way. A gene can confer resistance to several drug classes, so split Drug Class and count the gene toward each of its classes:

classes <- strsplit(detected[["Drug Class"]], "; ")
by_class <- data.frame(
  run_accession = rep(detected$run_accession, lengths(classes)),
  drug_class = unlist(classes),
  rpkm = rep(detected$rpkm, lengths(classes))
)
class_rpkm <- xtabs(rpkm ~ drug_class + run_accession, data = by_class)
top_classes <- names(sort(rowSums(class_rpkm), decreasing = TRUE))[1:10]
round(class_rpkm[top_classes, sample_order])
#>                                      run_accession
#> drug_class                            SRR41520897 SRR41520919 SRR41520874
#>   macrolide antibiotic                         40        5854      113961
#>   lincosamide antibiotic                       26        5856      113986
#>   streptogramin antibiotic                     26        5856      113985
#>   phenicol antibiotic                           0        4459         550
#>   fluoroquinolone antibiotic                 2843        1399        1203
#>   penicillin beta-lactam                     2170        1050         835
#>   aminoglycoside antibiotic                  2097         887         689
#>   cephalosporin                              1132         773         784
#>   disinfecting agents and antiseptics         775         573         600
#>   tetracycline antibiotic                     366         273         279
#>                                      run_accession
#> drug_class                            SRR41520873 SRR41520878 SRR41520882
#>   macrolide antibiotic                      42996         580         767
#>   lincosamide antibiotic                    43519         133         133
#>   streptogramin antibiotic                  43525         102          79
#>   phenicol antibiotic                       57765         315         464
#>   fluoroquinolone antibiotic                 1369         852        1286
#>   penicillin beta-lactam                     1035         697        1025
#>   aminoglycoside antibiotic                  1020         159         265
#>   cephalosporin                               667         395         641
#>   disinfecting agents and antiseptics         493         434         686
#>   tetracycline antibiotic                     246         558         767
#>                                      run_accession
#> drug_class                            SRR41520894 SRR41520884
#>   macrolide antibiotic                         23          20
#>   lincosamide antibiotic                        2          17
#>   streptogramin antibiotic                      2          19
#>   phenicol antibiotic                          15           9
#>   fluoroquinolone antibiotic                   33           3
#>   penicillin beta-lactam                       86           1
#>   aminoglycoside antibiotic                    86           3
#>   cephalosporin                                98           5
#>   disinfecting agents and antiseptics          22           2
#>   tetracycline antibiotic                      44          18

From here, the detected table can be reshaped for other analyses, for example a runs × genes RPKM matrix for diversity or ordination:

gene_matrix <- xtabs(rpkm ~ run_accession + `ARO Term`, data = detected)
dim(gene_matrix)
#> [1]   8 150

Read-level and contig-level results

RGI can find resistance genes in metagenomes in two ways (RGI documentation):

  • Read level (rgi bwt, used by rgi_runs() and rgi_local()). Each read is aligned to CARD’s reference sequences with KMA, a k-mer-based aligner (or Bowtie2 or BWA), and reads are counted per gene. This is sensitive, works at low sequencing depth, and gives abundances, but each read is short, so it can’t tell closely related genes or alleles apart, confirm that a whole gene is present, check for resistance mutations, or link a gene to the genome it sits in.
  • Contig level (rgi main). Reads are first assembled into contigs (e.g. with SPAdes or MEGAHIT); RGI then predicts genes on the contigs and compares them with CARD, classifying each hit as Perfect, Strict or Loose (the options of CARD’s RGI web portal). Whole genes, their variants and their neighbouring genes give stronger evidence of resistance, but genes in organisms with low coverage may not assemble.

sra2lab provides only read-level, k-mer-based alignment results; it does not assemble contigs or run rgi main. CZ ID’s AMR pipeline (CZ ID AMR Pipeline Workflow) shows a fuller approach: after quality filtering and removing host (human) reads, it runs both read-level alignment (rgi bwt, with KMA) and contig assembly (SPAdes) followed by rgi main, and combines the two, also predicting each gene’s pathogen of origin. To follow that approach, use rgi_runs() results for screening and abundance, and confirm genes of interest with assembly and rgi main, for example in CZ ID or with your own assembly pipeline. Note also that rgi_runs() maps all reads, without quality filtering or host read removal, so host reads count toward each run’s total in the RPKM calculation above.

Next steps

  • Map the rest of the BioProject with rgi_runs(runs); already mapped runs are skipped.
  • Map reads you already have on disk with rgi_local(), which finds each specimen’s R1 and R2 files by specimen ID and gives them to RGI as pairs.
  • Get taxonomic or functional profiles from the same downloads with multiprocess_runs(), e.g. multiprocess_runs(runs, process_path = c("sylph", "rgi")).
  • Keep the alignments (keep_bam = TRUE) to compute other normalisations, such as those the RGI documentation suggests.
  • Confirm genes of interest at the contig level, by assembling the reads and running rgi main, or with CZ ID’s AMR pipeline (see above).

References

Alcock BP, Huynh W, Chalil R, et al. CARD 2023: expanded curation, support for machine learning, and resistome prediction at the Comprehensive Antibiotic Resistance Database. Nucleic Acids Research. 2023;51(D1):D690–D699. https://doi.org/10.1093/nar/gkac920

RGI: Resistance Gene Identifier (source code and documentation). https://github.com/arpcard/rgi

CARD. Resistance Gene Identifier (RGI) web portal. https://card.mcmaster.ca/analyze/rgi

CZ ID Help Center. AMR Pipeline Workflow. https://chanzuckerberg.zendesk.com/hc/en-us/articles/15091031482644-AMR-Pipeline-Workflow