Chapter 3: Data Input and Structures
Preamble
Learning Outcomes
The objective of this chapter is to introduce you to the manner in which dartRverse stores genotype data and associated metadata, and how to input and export data from dartRverse (I/O).
After completing this chapter you should have a basic understanding of the fundamentals of dartRverse storage including the genotypes for each individual and associated metadata for each locus and each individual.
You will also learn how to read your data into dartRverse and how to output the results of your analyses and manipulations. An important method for outputting data is to save your dataset in a compact binary form for later use. In this chapter, we also cover the output of data in a form for use by third-party software packages.
This is an introductory guide. You should be empowered to expand your knowledge beyond the basics presented here by exploring the help on these topics and associated scripts, and by applying the knowledge in other tutorials to come.
Prerequisites
![]()
RStudio is an integrated development environment (IDE) with a graphical user interface (GUI) used to manage R workflow and so to work through this chapter, you will need to have already completed Chapter 1 RStudio Refresher. For more advanced treatment refer to the official documentation.
![]()
You may also find it helpful to listen to the podcast summary of the overview material in this chapter.
Mastering Data Input and Storage (mp3)
Workflow
![]()
You will have already established a project and associated working directory and downloaded the required data files to your working directory. The Tutorial Pane in RStudio should contain the Worked Examples and Exercises.
The workflow from this point follows a formula.
- Theory, unencumbered by competing options and technical asides;
- Worked Examples where you are led through analyses with sample code;
- Exercises where you are left on your own to integrate the knowledge you have gained in a problem-solving context.
- Review the learning outcomes and the section on Where have we come? to confirm that you are moving to the next chapter with all that is required under your belt.
Accessing Worked Examples and Exercises
We covered how to access the worked examples and exercises in Chapter 1. Briefly, if you have not done so already:
source("http://georges.biomatix.org/storage/app/media/eBook1/eBook_data_download.txt")
install.packages("dartRverse")
library(dartRverse)
gl.set.verbosity(3)
install.packages(c("remotes", "learner")
remotes::install_github("Biomatix/eBook1")
library(eBook1)
Session 3.1: Introduction to DArTSeq
Sequencing
Diversity Arrays Technology Pty Ltd (DArT) is a private company that specialises in genotyping by sequencing. Their approach is one of genome complexity reduction. But what does this mean?
Basically, DArTSeq is a method that extracts reproducible genomic variation across many individuals at an affordable cost. The technique digests genomic DNA using pairs of restriction enzymes (cutters) (Figure 3-1). When the DNA is cut at two locations within a reasonable distance of each other, the fragment is available for sequencing using the Illumina short-read platforms. Hence, the data are representational in the sense that they are generated for a random but reproducible selection of small fragments of sequence only, fragments that exhibit variation at the level of single base pairs (SNPs).
The first step in the process involves the selection of restriction enzymes that provide the best balance between getting an adequate fraction of the genome represented, an adequate read depth for each fragment, and adequate levels of polymorphism. This is species-specific and so requires some initial optimisation.

Once the best restriction enzymes are selected, say PstI (recognition sequence 5′-CTGCA|G-3′) and SphI (5’-GCATG|C-3’), then the DNA is digested, and various adaptors are added to the sequence fragments to allow Illumina short-read sequencing to proceed. These additional terminal sequences include a barcode to allow disaggregation of the sequences for each sample during later analysis.
The fragments of DNA selected by this process are sequenced in an abbreviated process to yield a set of raw “sequence tags” each of around 75 bp. They are filtered on sequence quality, particularly in the barcode region, truncated to 69 bp and stacked by sequence similarity. A series of proprietary filters are then applied to select those sequence tags that include a reliable SNP marker.
In particular, one third of samples are processed twice as technical replicates, from DNA and using independent adaptors, through to allelic calls. Scoring consistency (repeatability) is used as the main selection criterion for high-quality and low error-rate markers.
These DArT analysis pipelines have been tested against hundreds of controlled crosses to verify Mendelian behaviour of the resultant SNPs as part of their commercial operations.
When you come to publish, you may receive requests to be more elaborative than you are able to, because of the proprietary nature of the pipelines. DArT Pty Ltd is a private company and needs to hold some of its proprietary analyses in-house. Note that other companies with whom you interact, including Illumina, do the same. The work is reproducible in that using the same service/equipment on the same samples will yield the same result. Most journals accept this.
The SNP dataset
SNPs, or single nucleotide polymorphisms, are single base pair mutations at a nuclear locus (Figure 3-2). That nuclear locus is represented in the dataset by two sequence tags which, at a heterozygous locus, take on two allelic states, one referred to as the reference state, the other as the alternate or SNP state.
Because it is extremely rare for a mutation to occur twice at the same site in the genome (perhaps with the exception of Eucalypts), the SNP data are considered to be effectively biallelic. Sites with more than two states that occur rarely are typically eliminated in the quality control steps as they are bundled with multiallelic sites arising from multiple copy sequences (e.g. as would arise from gene duplications) removed during preliminary filtering.
The data can be represented in a table of SNP bases (A, T, C or G), with two states for each individual at each locus in diploid organisms (Table 3-1). The data shown in Table 3-1 are the base pairs on each haplotype of the sequence tag associated with the locus. The haplotypes are not phased with the reference and alternate alleles chosen arbitrarily.
The reference allele is arbitrarily taken to be the most common allele, so 0 is the score for homozygous reference, and 2 is the score for homozygous alternate or SNP state. NA indicates that the SNP could not be scored (Table 3-2).
Table 3-2 shows the form the data are stored in dartRverse, though note that it departs from the coding arrangement used by DArT.
Some sequence tags might contain more than one SNP, in which case they are likely to be closely linked when passed from parent to offspring. These may need consideration when preparing your data for analysis. Note that multiple SNPs occurring in the same sequence tag are each represented as a separate data record in the dataset.
The SNP data are provided in two forms by DArT, which will be described later.
SilicoDArT
As well as individuals varying in allelic composition at SNP sites, they can also vary at the restriction sites used to pull the representation from the genome. A mutation at one or both of the restriction sites will result in allelic dropout or null alleles. The presence or absence of particular sequence tags across individuals provides a source of information additional to the SNP data. DArT refers to these data as SilicoDArT markers.
Broadly, SilicoDArT markers can be considered analogous to AFLPs (Amplified Fragment Length Polymorphisms).
DArT provide this second dataset of presence (1) or absence (0) scores for sequence tags across individuals (Table 3-3). The filtering pipeline applied to generate these data has been highly optimised for reliability, so do not be tempted to use the null alleles (missing data) present in the SNP dataset.
Note: Unlike the SNP data, NA represents a value that is truly missing – the state, presence or absence of the sequence tag could not be determined. Note also that the SilicoDArT dataset will include the presence or absence of sequence tags that do not contain a SNP.
Where have we come?
![]()
The above Session was designed to give you a very brief overview of the DArT pipelines for producing SNP and associated data. Having completed this Session, you should now be familiar with the following concepts.
- The concept of a SNP marker and how SNP markers are generated.
- The distinction between DArTSeq and SilicoDArT datasets.
- The coding used for SNP genotypes – 0 for homozygous reference, 2 for homozygous alternate, 1 for heterozygous, and NA for ‘missing’.
- The coding used for SilicoDArT genotypes – 0 for absent, 1 for present, and NA for missing.
Session 3-2: Getting data into dartRverse
A sensible workflow
![]()
Let us begin by jumping the gun and defining a sensible pipeline for entering your data, as a context for the material in this and subsequent Sessions.
- Examine the data provided by DArT in Excel to confirm that it conforms to expectations of the dartRverse package.
For the SNP data, there needs to be anAlleleIDcolumn, and the start and end columns of the locus metadata need to be defined by the columns headed by asterisks. The row with the locus metadata labels needs to be the same row that holds the individual (= specimen or sample labels). This is usually the case, but some older datasets may need a little modification.
For the SilicoDArT data, there needs to be aCloneIDcolumn and the locus metadata needs to be defined by the columns headed by asterisks. - Prepare the metadata associated with each individual. This dataset, stored in csv format, contains at a minimum the individual/specimen labels in a column headed
id, and a population column that assigns individuals to groups or populations in a column headedpop. Other columns are optional but might include latitude, longitude of capture, sex, or other possible groupings or other information related to the individuals. - Read the data into dartRverse.
We elaborate on this workflow in the sections that follow.
How dartRverse stores SNP data
![]()
The package dartRverse relies on the SNP data being stored in a compact form using a bit-level coding scheme. SNP data coded in this way are held in a genlight object defined in R package adegenet, described in Analysing genome-wide SNP data using adegenet 2.0.0 by Thibaut Jombart and Caitlin Collins.
The complex storage arrangement of genlight objects is hidden from the user because it is accompanied by a number of “accessors”. These allow the data to be accessed in a way similar to manipulating standard objects in R, such as lists, vectors and matrices.
A genlight object can be considered a matrix containing the SNP data encoded in a particular way (Figure 3-3). The matrix entities (rows) are the individuals, and the attributes (columns) are the SNP loci. In the body of this individual by locus matrix are the SNP data, coded as 0 for homozygous reference state, 1 for heterozygous, and 2 for homozygous alternate (or SNP) state.
Note: This coding is quite different from that used by DArT in their 1-Row and 2-Row csv files provided as part of their report.
Note also that a genlight object used by dartRverse differs in some important respects from the default genlight object of adegenet (a dartR genlight object is a superset of an adegenet genlight object). By this we mean that all functions in the adegenet package work on dartR genlight objects, but dartR genlight objects have other essential components. So creating a genlight object to hold your data manually from a vcf or csv format requires a few steps in addition to importing the data to an adegenet genlight object.
Genlight objects not only contain SNP data, but also allow attachment of locus metadata to loci and of individual metadata to individuals/samples (Figure 3-3). The data and metadata are dataframes and handled sensibly by dartRverse following {adegenet} accessors [e.g. nLoc(), nInd(), pop()].
Locus metadata
The locus metadata included in the genlight object are those provided as part of your DArT report. These metadata are obtained from the DArT csv file when it is read into the genlight object. The locus metadata are held in an R data.frame that is associated with the SNP data as part of the genlight object.

The locus metadata would typically include:
| SNP: | the mutational change and its position in the sequence tag, referenced from zero |
| SnpPosition: | position (zero-based, 0= first base) in the sequence tag of the defined SNP variant base |
| TrimmedSequence: | (optional) The sequence containing the SNP or SNPs (the sequence tag), trimmed of adaptors. |
| CallRate: | proportion of samples for which the genotype call is non-missing (that is, not "-") |
| OneRatioRef: | proportion of samples for which the genotype score is 0 |
| OneRatioSnp | proportion of samples for which the genotype score is 2 |
| FreqHomRef: | proportion of samples homozygous for the Reference allele |
| FreqHomSnp: | proportion of samples homozygous for the Alternate (SNP) allele |
| FreqHets: | proportion of samples which score as heterozygous, that is, scored as 1 |
| PICRef: | polymorphism information content (PIC) for the Reference allele |
| PICSnp: | polymorphism information content (PIC) for the SNP |
| AvgPIC: | average of the polymorphism information content (PIC) of the Reference and SNP alleles |
| AvgCountRef: | sum of the tag read counts for all samples, divided by the number of samples with non-zero tag read counts, for the Reference allele row |
| AvgCountSnp | sum of the tag read counts for all samples, divided by the number of samples with non-zero tag read counts, for the Alternate (SNP) allele row |
| RepAvg: | proportion of technical replicate assay pairs for which the marker score is consistent |
In addition, dartRverse calculates the minor allele frequency and estimates of read depth and stores them in the locus metadata.
These metadata variables are held in the genlight object as part of a data.frame called loc.metrics.
Depending on the report from DArT you may have additional, fewer or different loc.metrics (e.g. TrimmedSequence may be available only on request).
These metadata are used by dartRverse for various purposes, so if any are missing from your dataset, some analyses will not be possible. For example, TrimmedSequence is used to generate output for subsequent phylogenetic analyses that require estimates of base frequencies and transition and transversion ratios.
AlleleID is essential (with its very special format), and dartRverse scripts for loading your data sets will terminate with an error message if this is not present.
Individual metadata
Individual (=specimen/sample) metadata are user-specified, and do not come from DArT. Individual metadata are held in a second dataframe associated with the SNP data in the genlight object (Figure 3-3).
Two special individual metrics are:
id |
Unique identifier for the individual or specimen that links back to the physical sample |
pop |
A label for the biological population from which the individual was drawn |
Individual metrics are supplied by the user by way of a metadata file, provided at the time of reading the SNP data into the dartR genlight object. The metadata file is a comma-delimited file, usually named ind_metrics.csv or similar, that contains labelled columns. The file must have a column named id that contains the individual (=specimen or sample labels) and a column named pop, which contains the populations to which individuals are assigned.
These special metrics can be accessed using:
pop(gl)
popNames(gl)
indNames(gl)
A number of other user-defined metrics can be included in the metadata file. Examples of user-defined metadata for individuals include:
sex: |
Sex of the individual (Male, Female) |
maturity: |
Maturity of the individual (Adult, Subadult, Juvenile) |
lat: |
Latitude of the location of collection |
long: |
Longitude of the location of collection |
These optional data are provided by the user in the same metadata file used to assign id labels and assign individuals to populations at the time of reading in the data.
The individual metadata are held in the genlight object as a dataframe named ind.metrics.
Flags
The genlight object used by dartRverse has some additional information not normally accessed by the user. If these data are not in the genlight object, various functions may throw an error.
To ensure your manually generated genlight object (say, converted from a vcf file) is compliant, be sure to use
gl <- gl.compliance.check(gl)
How dartRverse stores SilicoDArT data
![]()
dartRverse also stores SilicoDArT presence/absence data in a genlight object but distinguishes the data from SNP data by setting ploidy=1.
The locus metadata would typically include:
| AlleleSequence: | Sequence of the tag which is present in samples with genotype score "1" |
| TrimmedSequence: | Same as the full sequence, but with removed adaptors in short marker tags |
| AvgReadDepth: | Sum of the tag read counts for all samples, divided by the number of samples with non-zero tag read counts. |
| StDevReadDepth: | Standard deviation of the number of tag reads for all samples with non-zero tag read counts |
| CallRate: |
Proportion of samples for which the genotype call is either |
| CloneID: | Unique identifier of the sequence tag |
| OneRatio: |
Proportion of samples for which the genotype score is |
| PIC: | Polymorphism Information Content |
| Qpmr: | Average of the normalised non-zero tag read counts divided by the standard deviation of the normalised non-zero tag read counts (If standard deviation is zero or near zero, the Qpmr value will be 100). |
| Reproducibility: | Proportion of technical replicate assay pairs for which the marker score is consistent |
Note that the locus metadata supplied by DArT may vary from service to service. The SilicoDArT data and associated metadata can be accessed in the same way as for SNP data, as described above.
Reading DArT files into a genlight object
SNP genotypes
SNP data can be read into a genlight object using gl.read.dart().
This function intelligently interrogates the input csv file to determine:
- if the file is a 1-row or 2-row format, as supplied by DArT Pty Ltd.
- the number of locus metadata columns to be input before reading the SNP data themselves.
- the number of lines to skip at the top of the csv file before reading the specimen IDs and then the SNP data themselves.
- if there are any errors in the data.
An example of the function used to input data is as follows:
gl <- gl.read.dart(filename="sample_data_2Row.csv", ind.metafile="sample_metadata.csv")
The filename specifies the csv file provided by DArT, and the ind.metafile parameter specifies the csv file that contains metrics associated with each individual (id, pop, sex, environmental data, etc).
The gl.read.dart function
- transfers the SNP states to the body of the genlight object (as 0, 1, 2, NA);
- transfers the locus metadata (call rate, AvgPIC, etc) to the locus metadata dataframe (
gl@other$loc.metrics) and calculates a few more; - transfers individual metadata (plate, Specimen id, etc) to the individual metadata dataframe (
gl@other$ind.metrics); and - transfers additional individual metadata provided via the
ind.metafileparameter to the individual metadata dataframe.
The resultant dartR genlight object contains the SNP genotypes, the individual metadata and the locus metadata.
SilicoDArT genotypes
SilicoDArT data can be read into a genlight object using gl.read.silicodart(). This function intelligently interrogates the input .csv file to determine
- the number of locus metadata columns to be input (the first typically being
CloneIDand the lastReproducibility). - the number of lines to skip at the top of the
.csvfile before reading the specimen IDs and then the SilicoDArT data themselves. - if there are any errors in the data.
An example of the function used to input data is as follows:
gl <- gl.read.silicodart(
filename="sample_data_silicodart.csv", ind.metafile="sample_metadata.csv")
The filename specifies the .csv file provided by DArT, and the ind.metafile parameter specifies the .csv file that contains metrics associated with each individual (e.g. id, pop, sex, environmental data, etc).
The resultant genlight object contains the SilicoDArT presence/absence genotypes, the individual metadata and the locus metadata.
Reading non-DArT files into a dartR genlight object
If you are working with data that have not been prepared by DArT, you can still input the data to dartRverse provided you can get it into the appropriate format.
Unfortunately the .vcf format is not a strict standard, so it has been difficult to capture all of the variations in our gl.read.vcf() script. Nevertheless, gl.read.vcf() should be your first port of call.
As with gl.read.dart(), the script requires the name of the data file (.vcf) and the name of an ind.metafile that contains the metadata for individuals.
gl <- gl.read.vcf(vcffile="Arabian_Oryx.vcf",
ind.metafile="Oryx.ind.metadata.csv")
You can try this for yourself by navigating to and undertaking the Exercise on the Arabian Oryx, reading a vcf file.
If you do have difficulties, another method for inputting data from a .vcf file to dartRverse is to extract the genotypes in A/T format (- for missing) as a comma-delimited .csv file, then prepare two additional .csv files, one with the locus metrics and one with the individual metrics.
The locus metrics should include only those locus attributes that cannot be calculated from the data. The locus names should correspond to those in the genotype matrix. Similarly, the individual names should correspond to those in the genotype matrix.
The three files can then be read into dartRverse with
gl.read.csv(filename=<genotype csv name>,
ind.metafile=<individuals csv name>,
loc.metafile=<locus csv name>, verbose=3)
Session 3-3: Getting data out of dartRverse
Saving a genlight object
![]()
Reading the data in from an Excel spreadsheet and converting to a genlight object takes a lot of computation, and so time. You will also have done some tidying up of the data. It is sensible to save your genlight object in binary form using
gl.set.wd(getwd())gl.save(gl,file="tmp.RData")and then read it in again with
gl.new <- gl.load("tmp.RData")
Saving genotypes as a csv file
The function
write.csv(as.matrix(gL), "genotypes.csv")
will write the genotypes to a .csv file with the loci as column headings and the individuals as row headings.
Exporting data for use by third party software
![]()
Package dartRverse has options for exporting a genlight object to a format for input to third-party software packages.
Examples include:
gl2plink() |
Exports a genlight object into PLINK format. PLINK is a widely used, open-source software toolset for genome-wide association studies (GWAS) and population-based genetic analyses. |
gl2genepop() |
Exports a genlight object into GENEPOP format. GENEPOP is a software package designed for population genetics analyses. It performs tests for Hardy–Weinberg equilibrium, linkage disequilibrium, genetic differentiation, and calculates F-statistics from allele frequency data, typically for microsatellite or SNP markers. |
gl2faststructure() |
Exports a genlight object into fastSTRUCTURE format. fastSTRUCTURE is software designed to infer population structure from large-scale genotype (SNP) data. |
gl2fasta() |
Exports the trimmed sequence tags or SNPs into standard fastA format. |
gl2phylip() |
Calculates a Euclidean distance matrix from the genotypes and exports the matrix in a form suitable for the Phylip distance phylogeny analyses. |
A full list of conversion functions can be obtained by typing
??gl2 (without a return)
and examining the pulldown menu.
Session 3-4: Worked Examples
Background
Here we introduce a dataset that will be used in the worked examples in this and following chapters. It is drawn from studies of the Canberra earless dragon (Tympanocryptis lineata), a critically endangered species that is now found in a few remaining patches of lowland natural temperate grassland in the Australian Capital Territory. They are relatively sedentary, moving up to 100 metres in six weeks and have home ranges between 0.1 and 0.4 hectares. One would expect this low rate of movement and presumably dispersal to be reflected in the genetic structure of the species across isolated patches.
The ACT Government provides a link to the information on the Canberra earless dragon, including conservation planning at Territory and National level.

Monitoring of the species showed a rapid decline in numbers between 2002 and 2006, a decline that has continued to the point of bringing the species to the brink of extinction. A study of genetic diversity is among the many initiatives to build the knowledge necessary to stem and reverse this decline.
- Are the sub-populations of the species in their isolated remnant patches losing genetic diversity to a point where they will find it difficult to bounce back even with intervention?
- What strategies can be adopted to maximise genetic diversity in each of the declining sub-populations?
These are big questions. Answering them is beyond the scope of this introductory eBook. Our objective here is to use the data collected between 2002 and the present to illustrate, by way of worked examples, the techniques within the scope of this eBook. We start in Chapter 3 by pulling the data into dartRverse, examining the data, and outputting the data in various forms.
The data used in this Worked Example were collected as research by PhD student Ryan Colley and are unpublished at the time of writing. We have modified the data heavily for the sake of illustration, so they should not be used for any other purpose. If you wish to access the original data, contact the originators directly.
Worked Example: SNP Data
This worked example on the Canberra earless dragon illustrates how to input data into dartRverse, some basic functions for assessing whether the input was successful, and how to save the data in compact binary form for later use.
Navigate to the Worked Examples for Chapter 3.
Once you have input the data and are satisfied with it, you will be asked to save it in binary form for use in the next chapter.
Exercises
We have held your hand through the Worked Examples. It is time to integrate what you have learned with some exercises on input, storage in defined data structures and output of SNP and SilicoDArT data.
Navigate to the RStudio Tutorial Pane and then open the session eBook. Navigate to the Exercises for Chapter 3.
Winding up
Where have we come?
![]()
In this Session, we covered a range of topics on data entry, storage of data and some preliminary approaches to examining those data.
Having completed the Session, you should understand
- What is a sensible pipeline for preliminary handling of your SNP data.
- How a genlight object is organised in terms of the SNP scores (which are different from the scores used by DArT) and how locus and sample metadata are associated with the genotypes.
- The different types of locus metadata generated by DArT, and how to look up what each metric means.
- How to read data from DArT into a genlight object.
- How to read data generated independently from DArT into a genlight object.
- How to interrogate the locus and individual (specimen/sample) metadata.
- How to save a genlight object (genotypes, individual metadata, locus metadata) into compact binary form for later use.
- How to output data for use by third-party software.
Ende



