Skip to contents

RGI’s read-mapping command, rgi bwt, writes one set of results per sample: a table of the CARD resistance genes that reads mapped to, with how many reads and how much of each gene they covered, and a summary of the sample’s mapping. rgi_aggregate() reads all of a project’s results into one tibble, with one row per sample and resistance gene, drops genes with too little support, turns read counts into abundances that can be compared between samples, and joins the samples’ metadata (subject, date, body site, …). Every other rgi2lab function starts from that tibble.

Files you need

rgi2lab works on files you already have, made by RGI’s read-mapping command, rgi bwt (usually through sra2lab), and downloaded from NCBI. A typical analysis directory looks like this:

~/projects/
├── localDB/                            <- CARD data loaded by RGI (shared)
└── PRJNA1556220/                       <- analysis directory (working directory)
    └── data/
        ├── PRJNA1556220_runs.csv       <- run metadata
        └── rgi/                        <- rgi bwt results, per run:
            ├── SRR41520873_kma.gene_mapping_data.txt
            ├── SRR41520873_kma.overall_mapping_stats.txt
            └── ...

CARD. rgi bwt maps each sample’s reads to the reference sequences of the Comprehensive Antibiotic Resistance Database (CARD), loaded with rgi load --local into localDB. rgi2lab never reads the database: what each gene is (its AMR gene family, the drug classes it confers resistance to, and its resistance mechanism) is already in the results. But the results depend on the CARD version as well as the RGI version, so record both for your methods (rgi database --version --local).

Run metadata. sra2lab::get_bioproject_runs() returns one row per SRA run, with the BioSample attributes the submitters gave (subject, collection date, body site, …). Save it next to the results:

runs <- sra2lab::get_bioproject_runs("PRJNA1556220")
write.csv(runs, "data/PRJNA1556220_runs.csv", row.names = FALSE)

For local reads mapped with sra2lab::rgi_local(), use your own specimen table instead, with one row per specimen ID.

The RGI results come from sra2lab::rgi_runs() or rgi_local(): for each sample and aligner, files named <id>_<aligner>[_wildcard][_other_models].<output>. rgi2lab reads two of them: gene_mapping_data.txt, the reads mapped to each resistance gene, and overall_mapping_stats.txt, the sample’s total and mapped reads, which are needed for reads per kilobase per million (RPKM). Keep them together in one directory. See vignette("rgi-workflow", package = "sra2lab").

The example data

rgi2lab ships the rgi bwt results of 18 runs from BioProject PRJNA1556220, “Microbiome changes in the peri-heart transplant setting”, mapped with sra2lab::rgi_runs() (KMA aligner, CARD 4.0.2): the 8 runs of the sra2lab RGI vignette, plus repeat stool and perirectal swabs from the same subjects, so that five subjects have two to six samples each. They are the same runs as the example data of sylph2lab and funprofiler2lab. It also ships the run table for all 67 runs of the BioProject. rgi_example() gives their paths, which stand in for data/rgi and data/PRJNA1556220_runs.csv below.

Read the results

Point rgi_aggregate() at the directory of results. It reads every file ending in .gene_mapping_data.txt, and the overall_mapping_stats.txt next to each:

library(rgi2lab)

rgi_dir <- rgi_example("results")   # in a real analysis: "data/rgi"
head(list.files(rgi_dir))
#> [1] "SRR41520862_kma.gene_mapping_data.txt"    
#> [2] "SRR41520862_kma.overall_mapping_stats.txt"
#> [3] "SRR41520863_kma.gene_mapping_data.txt"    
#> [4] "SRR41520863_kma.overall_mapping_stats.txt"
#> [5] "SRR41520865_kma.gene_mapping_data.txt"    
#> [6] "SRR41520865_kma.overall_mapping_stats.txt"

genes <- rgi_aggregate(rgi_dir)
#> 1221 of 2469 gene detections were below `min_coverage` = 50% or `min_reads` = 0 and were left out.
genes
#> # A tibble: 1,248 × 35
#>    sample_id   aro_term gene_label aligner include_wildcard include_other_models
#>    <chr>       <chr>    <chr>      <chr>   <lgl>            <lgl>               
#>  1 SRR41520862 MrmA     MrmA       kma     FALSE            FALSE               
#>  2 SRR41520862 CfxA3    CfxA3      kma     FALSE            FALSE               
#>  3 SRR41520862 tet(Q)   tet(Q)     kma     FALSE            FALSE               
#>  4 SRR41520862 tet(O)   tet(O)     kma     FALSE            FALSE               
#>  5 SRR41520862 dfrF     dfrF       kma     FALSE            FALSE               
#>  6 SRR41520862 ErmB     ErmB       kma     FALSE            FALSE               
#>  7 SRR41520862 SAT-4    SAT-4      kma     FALSE            FALSE               
#>  8 SRR41520862 tet(W)   tet(W)     kma     FALSE            FALSE               
#>  9 SRR41520862 APH(3')… APH(3')-I… kma     FALSE            FALSE               
#> 10 SRR41520862 gadW     gadW       kma     FALSE            FALSE               
#> # ℹ 1,238 more rows
#> # ℹ 29 more variables: all_mapped_reads <dbl>, rpkm <dbl>,
#> #   relative_abundance <dbl>, average_percent_coverage <dbl>,
#> #   reference_length <dbl>, total_reads <dbl>, aro_accession <chr>,
#> #   amr_gene_family <chr>, drug_class <chr>, resistance_mechanism <chr>,
#> #   reference_model_type <chr>, reference_db <chr>,
#> #   alleles_with_mapped_reads <dbl>, …

Each row is one resistance gene detected in one sample. The first columns are the ones you will use most:

Column Meaning
sample_id the sample, from the file name (the run accession for sra2lab::rgi_runs())
aro_term the gene, as named in CARD’s Antibiotic Resistance Ontology (ARO), e.g. ErmB or tet(Q)
gene_label a label for plots (the ARO term)
aligner, include_wildcard, include_other_models how the sample was mapped, from the file name
all_mapped_reads reads mapped to the gene
rpkm reads per kilobase of gene per million sequenced reads (see Abundances)
relative_abundance the gene’s share (%) of the sample’s resistance gene content
average_percent_coverage share of the gene’s length covered by reads (%)
reference_length length of the gene’s reference sequence (bp)
total_reads reads sequenced for the sample, from overall_mapping_stats.txt
aro_accession, amr_gene_family, drug_class, resistance_mechanism CARD’s identifier and classification of the gene

The other columns of gene_mapping_data.txt follow, with their names in snake_case (Average MAPQ (Completely Mapped Reads) becomes average_mapq_completely_mapped_reads), and then rgi_file, the file each row came from.

CARD often gives a gene several gene families, drug classes or mechanisms, separated by "; "; a multidrug efflux pump, for example, confers resistance to many drug classes. rgi_heatmap() and rgi_feature_abundance() split these, so a gene counts towards each.

Mapping statistics

rgi_mapping_stats() reads each sample’s overall_mapping_stats.txt: how many reads were sequenced (both reads of a pair count), and how many mapped to CARD:

stats <- rgi_mapping_stats(rgi_dir)
stats[, c("sample_id", "total_reads", "mapped_reads", "percent_mapped")]
#> # A tibble: 18 × 4
#>    sample_id   total_reads mapped_reads percent_mapped
#>    <chr>             <dbl>        <dbl>          <dbl>
#>  1 SRR41520862    12750611        16996         0.133 
#>  2 SRR41520863    12160972        27207         0.224 
#>  3 SRR41520865    12748266        14867         0.117 
#>  4 SRR41520867    13057566        12520         0.0959
#>  5 SRR41520868    12267248        43867         0.358 
#>  6 SRR41520869    12864553        61008         0.474 
#>  7 SRR41520870    12849541       767488         5.97  
#>  8 SRR41520873    12741930       972846         7.63  
#>  9 SRR41520874    12698830      1129212         8.89  
#> 10 SRR41520876    12316026        11140         0.0905
#> 11 SRR41520878     7241566        20808         0.287 
#> 12 SRR41520879    13169340        23579         0.179 
#> 13 SRR41520882    11976553        49270         0.411 
#> 14 SRR41520884    11287077         3517         0.0312
#> 15 SRR41520894    10765452         3236         0.0301
#> 16 SRR41520897    12883126       131535         1.02  
#> 17 SRR41520902    20700103        66006         0.319 
#> 18 SRR41520919    24319182       339261         1.40

Only a small share of reads map to resistance genes, as expected: most reads come from other genes, or from the human host. Here it is 1-9% in the skin swabs, which carry abundant staphylococcal resistance genes, and below 0.5% in most gut samples. It is a quick quality check: a sample with very few reads, or a share far from others of its kind, deserves a look. rgi_aggregate() uses total_reads to compute RPKM.

Filtering

Reads can map to a short stretch of a gene that it shares with other genes, without the gene being present. A gene that is really there should be covered along most of its length, so by default rgi_aggregate() keeps only genes with at least 50% average coverage (as in the sra2lab RGI vignette) and says how many it dropped. Here, about half of the detections are dropped:

all_genes <- rgi_aggregate(rgi_dir, min_coverage = 0)
c(all = nrow(all_genes), kept = nrow(genes))
#>  all kept 
#> 2469 1248

Set min_coverage higher for a stricter analysis, or min_coverage = 0 to keep everything and filter yourself (for example on average_mapq_completely_mapped_reads or completely_mapped_reads). min_reads also requires a minimum number of mapped reads.

The number of genes kept per sample:

table(genes$sample_id)
#> 
#> SRR41520862 SRR41520863 SRR41520865 SRR41520867 SRR41520868 SRR41520869 
#>          84          80          45          59         107         162 
#> SRR41520870 SRR41520873 SRR41520874 SRR41520876 SRR41520878 SRR41520879 
#>         111          35          41          35          76          83 
#> SRR41520882 SRR41520884 SRR41520894 SRR41520897 SRR41520902 SRR41520919 
#>          82          16          53          26         130          23

Samples with no resistance genes

A sample in which no gene passes the filters (or no read mapped to CARD at all) is not dropped: it keeps a single row with aro_term NA and abundances of 0, and rgi_aggregate() lists it in a message. That way it counts as a sample with no resistance genes in heatmaps and abundance tables, rather than vanishing from them. Remember this when counting genes per sample: count non-missing aro_terms, e.g. tapply(!is.na(genes$aro_term), genes$sample_id, sum).

Abundances

rgi bwt reports raw read counts, which grow with sequencing depth (more reads, more reads on every gene) and with gene length (a longer gene catches more reads). rgi_aggregate() adds two normalised abundances:

  • rpkm, reads per kilobase of gene per million sequenced reads: all_mapped_reads / (reference_length / 1000) / (total_reads / 1e6). It corrects for both depth and length, so it can be compared between samples and between genes, and it is what the plotting functions use by default. It needs total_reads, so it is NA for samples whose overall_mapping_stats.txt is missing.
  • relative_abundance, the gene’s share (%) of the sample’s length-normalised resistance gene reads, so a sample’s genes sum to 100%. It describes the make-up of the resistome, but not how much resistance there is: a sample with one gene has 100% of it, however few reads it had.

The total RPKM of each sample is a simple measure of its resistance gene load:

load <- tapply(genes$rpkm, genes$sample_id, sum)
round(sort(load, decreasing = TRUE))
#> SRR41520874 SRR41520873 SRR41520870 SRR41520919 SRR41520897 SRR41520869 
#>      117934      105823       80221       14801        7988        3906 
#> SRR41520882 SRR41520868 SRR41520902 SRR41520878 SRR41520863 SRR41520879 
#>        2823        2705        2201        1945        1489        1217 
#> SRR41520862 SRR41520876 SRR41520867 SRR41520865 SRR41520894 SRR41520884 
#>         987         640         598         556         277          42

Join sample metadata

Give the run table (or its path) as metadata. It is joined by matching sample_id to the table’s run_accession column:

genes <- rgi_aggregate(
  rgi_dir,
  metadata = rgi_example("runs")   # "data/PRJNA1556220_runs.csv"
)
#> 1221 of 2469 gene detections were below `min_coverage` = 50% or `min_reads` = 0 and were left out.

unique(genes[, c("sample_id", "host_subject_id", "isolation_source",
                 "collection_date")])
#> # A tibble: 18 × 4
#>    sample_id   host_subject_id isolation_source collection_date
#>    <chr>       <chr>           <chr>            <date>         
#>  1 SRR41520862 GOL_019         Stool Swab       2026-04-16     
#>  2 SRR41520863 GOL_017         Stool Swab       2026-04-03     
#>  3 SRR41520865 GOL_017         Perirectal Swab  2026-03-24     
#>  4 SRR41520867 GOL_015         Stool Swab       2026-05-12     
#>  5 SRR41520868 GOL_019         Stool Swab       2026-05-09     
#>  6 SRR41520869 GOL_016         Perirectal Swab  2026-04-09     
#>  7 SRR41520870 GOL_016         Perirectal Swab  2026-04-03     
#>  8 SRR41520873 GOL_017         Groin Swab       2026-03-24     
#>  9 SRR41520874 GOL_034         Groin Swab       2026-08-18     
#> 10 SRR41520876 GOL_015         Stool Swab       2026-05-17     
#> 11 SRR41520878 GOL_017         Perirectal Swab  2026-04-03     
#> 12 SRR41520879 GOL_017         Stool Swab       2026-03-27     
#> 13 SRR41520882 GOL_017         Perirectal Swab  2026-03-27     
#> 14 SRR41520884 GOL_003         Stool Swab       2025-09-16     
#> 15 SRR41520894 GOL_018         Stool Swab       2026-03-02     
#> 16 SRR41520897 GOL_015         Axilla Swab      2026-05-11     
#> 17 SRR41520902 GOL_003         Stool Swab       2025-09-09     
#> 18 SRR41520919 GOL_016         Axilla Swab      2026-03-30

Every gene now carries its sample’s subject, swab type and date, ready for plotting and modelling. A few things to know:

  • For sra2lab::rgi_local() results, or your own metadata, name the ID column with metadata_id, e.g. metadata_id = "specimen_id".
  • The metadata must have one row per sample; duplicated IDs are an error.
  • Samples with no metadata row are kept, with NA metadata, and listed in a warning, so a typo in an ID does not silently drop data.
  • Metadata columns that share a name with an rgi2lab column get the suffix _metadata.

Results made with several settings

sra2lab::rgi_runs() can map each sample with several aligners ("kma", "bowtie2", "bwa"), and with or without CARD’s Resistomes & Variants (include_wildcard) and other model types (include_other_models), giving one set of files per setting. rgi_aggregate() reads them all, records each row’s settings, and tells you when there is more than one. Keep one before plotting (the plotting functions stop otherwise, since a sample’s genes would be counted twice):

genes <- rgi_aggregate("data/rgi", aligner = "kma", include_wildcard = FALSE,
                       include_other_models = FALSE)

Sample IDs from other file names

Results from sra2lab are named <id>_<aligner>[_wildcard][_other_models].gene_mapping_data.txt. Files named otherwise get the file name without .gene_mapping_data.txt as their ID, and no settings. To take the ID from elsewhere in the path, pass a regular expression with sample_pattern; here, from the directory each file is in:

genes <- rgi_aggregate(
  Sys.glob("results/*/output.gene_mapping_data.txt"),
  sample_pattern = "(?<=results/)[^/]+"
)

results can also be a data frame you have already read, with the sample in sample_id or run_accession, and total_reads if you have it.

Reading the results with care

Read-level mapping is sensitive and gives abundances, but reads are short, so some caution is needed (see also the sra2lab RGI vignette):

  • Similar genes. Reads from closely related genes can map to several CARD references. In the example data, the Staphylococcus intermedius and Enterococcus faecalis chloramphenicol acetyltransferases always appear together, and are probably one gene.
  • Intrinsic genes. Many CARD genes, such as Escherichia coli’s efflux pumps and their regulators, are in every genome of a species and confer resistance only when mutated or overexpressed, so their presence says more about which species are there than about resistance.
  • Contamination. Some genes common in cloning vectors and reagents may, at low abundance, come from contamination rather than the sample. Negative controls help to tell.

Save the result

The tibble is ordinary data, so save it for the next steps of the analysis:

readr::write_csv(genes, "data/rgi_genes_combined.csv.gz")

and summarise it with the usual tools, for example the number of distinct genes detected per swab type:

detected <- genes[!is.na(genes$aro_term), ]
aggregate(aro_term ~ isolation_source, data = detected,
          FUN = function(x) length(unique(x)))
#>   isolation_source aro_term
#> 1      Axilla Swab       34
#> 2       Groin Swab       56
#> 3  Perirectal Swab      217
#> 4       Stool Swab      204

Next steps