This study is a comparison of the efficiency of three technologies used for Y chromosome capture and the next-generation sequencing (NGS) technologies applied for determining its whole sequence. Our main findings disclose that streptavidin–biotin magnetic particle-based capture methodology offers better and a deeper sequence coverage for Y chromosome capture, compared to chromosome sorting and microdissection procedures. Moreover, this methodology is less time consuming and the most selective for capturing only Y chromosomal material, in contrast with other methodologies that result in considerable background material from other, non-targeted chromosomes. NGS results compared between two platforms, NextSeq 500 and SOLID 5500xl, produce the same coverage results. This is the first study to explore a methodological comparison of Y chromosome capture and genetic analysis. Our results indicate an improved strategy for Y chromosome research with applications in several scientific fields where this chromosome plays an important role, such as forensics, medical sciences, molecular anthropology and cancer sciences. However there are many relevant details in the origins and functional evolution of Y chromosome when comparing Y/W genes (human/avian sex chromosomes) showing notable conservation of proto-sex chromosome expression patterns in both chromosomes3; or even comparing Y chromosome evolution across eight mammals identifying biases in gene content and the selective pressures that preserved the surviving ancestral genes4. Recent studies which compared 30 mammalian genomes reported that, despite gene gain and loss across the phylogeny, the eutherian ancestor retained a core set of 17 male-specific regions of Y chromosome genes5.The status of human Y chromosome evolution and its implications for genetics and medicine remain largely unknown. Recently published data have illustrated the need for further knowledge about the human Y chromosome, for a greater understanding of the characteristics and evolutionary forces that act on sex chromosomes, and for better tools to correctly interpret the Y chromosome’s history of long-term survival6. Previous studies have tried to present an empirical reconstruction of human MSY  evolution by sequencing the MSY of the rhesus macaque (Macaca mulatta), an Old World monkey, by comparing it to the human7, confirming that Y-linked genes were conserved in chimpanzees and humans, which diverged about six million years ago8.The Human reference genome sequence remains incomplete, as there are many satellite DNA-rich regions that continue uncharacterized9. Short-read as well as whole genome sequencing (WGS) based long-read mapping strategies are faltering even for non-repeat Y regions (NRY), where there is no meiotic recombination map and intrachromosomal repetitive sequences are abundant10.The Y chromosome is one of the chromosomes with the largest proportion of repeated sequences. It has more than 40 Mb of heterochromatic regions, and the current methodological limitation of sequencing such repeated regions is the main reason why the Y chromosome has not yet been fully sequenced11. For a proper characterization of complex genomic regions it is important to capture and sequence large adjacent DNA fragments. To date, several authors have achieved the capture of DNA segments larger than 20 kbp in length by Region-Specific Extraction (RSE) with minimal need of a reference DNA12. Chromosome capture methodologies followed by sequencing offer the ability to resolve complex genomic regions.Targeted enrichment is an approach to resolve some of those difficulties. There are dozens of methods for capturing different regions of the genome. The most common methods are known as “molecular inversion probe circularization”, multiplex PCR and hybridization capture methodsMitochondrial DNA (mtDNA) and the non-recombining region of the Y chromosome are the genetic markers most useful for phylogenetic and phylogeographic analyses for their specific female and male inheritance respectively. The Y-chromosome in particular, since it does not recombine, has changed over generations only through an accumulation of mutations, thereby ultimately creating patrilineal lines.14. The recent developments of Next Generation Sequencing (NGS) techniques allow us to analyze not only modern but ancient whole genomes as well, and these techniques can be used to estimate potential problems in ancient samples like contamination with modern DNA, by exploiting those molecular properties that would distinguish an endogenous human DNA from a modern exogenous contaminant16.Molecular anthropology allows us to virtually travel back to the time and date of the emergence of these different mutations, thus rebuilding the migrations of the past that evolved the current set of extant mitochondrial and Y chromosome lineages with good precision18. However, there are no validated capture techniques for the whole chromosome.Due to the high interest of sequencing and capturing the Y-chromosome in several fields, such as molecular anthropology, forensics and medical genetics, specific methodologies to study Y chromosome fragments, such as haplotype-specific extraction (HSE), have been developed that allow us to discern between chromosomes from mixtures from different Y chromosomal samples19. However, the capture of lesser-known, highly variable or more complex chromosomal regions, such as the Y chromosome, is considerably more challenging. The main reason is the difficulty of designing specific capture probes that can extract large chromosomal segments across potentially highly repetitive sequences based on a very sparse availability of unique target sequences. Moreover, the Y chromosome length and composition makes it complicated to have an efficient isolation method20.It remains a challenge to consolidate an effective methodology for the reliable capture of Y chromosomal regions through procedures that are common for other parts of the genome. The isolation of certain regions of the genome - such as several genes of interest or the entire exome - are routinely done in genetic analysis. In the case of target regions with well-known nucleotide sequences, the capture is easily accomplished, due to the specificity of target sequences and the option of designing a correspondingly large number of capture probes that densely cover a large percentage of the target region for probe hybridization21. Also, there is a major lack of knowledge in the genetic factors causing male infertility22. And finally, the haploid nature of the Y chromosome implies that any genetic alteration would immediately cause aberrant protein products for expressed genes that cannot be compensated by a second allele22. These questions have not been answered primarily due to the lack of adequate means for reliably enriching and studying the human Y chromosome.A successful enrichment of the Y chromosome versus other chromosomes will allow a deeper analysis of these regions. This will improve several essential applications in phylogenetic or forensic analysis as well as in translational research. For example, obtaining an accurate phylogenetic tree with all Y chromosome variants is not possible without using Next Generation Sequencing (NGS) analysis24.The development of NGS technologies has greatly expanded the field of genomics research by providing the possibility of unprecedented large-scale and high-throughput analyses. One of the most significant improvements has been focused on obtaining long range reads and bioinformatics analysis25.Currently, NGS technologies allow for the accurate processing of a large number of samples, including a more sensitive detection of variations on a population level, the discovery of causative variants and the verification of benign single/multiple-nucleotide polymorphisms). With targeted gene capture, the relative proportion of DNA fragments originating from targeted regions is greatly increased. Moderately complex and unique genomic areas can usually be analyzed by targeted gene capture. Examples are exons, specific genes and key players in functionally important biological pathways, extended segments including exons and introns, as well as promoters or highly conserved sequences in intronic regions26. More and more of reported NGS data is obtained by targeted gene capture, for example the successful confirmation of over 100 human genes implicated in syndromic and non-syndromic hearing loss25.An example of a commonly used NGS platform is the Illumina system, which produces up to 900 Gb of short, paired-end sequences 27. Moreover, successful genetic disease analysis through gene capture and NGS have been described for Essential tremor, Spine cerebellar ataxia, Charcot Marie Tooth disease, Friedreich ataxia, Ataxia-telangiectasia and Huntington’s disease25. Exome sequencing is also widely employed in clinical and research fields. Examples include the diagnosis of novel diseases and finding novel causative mutations for known disease phenotypes, used for particularly difficult-to-diagnose patients, prenatal diagnosis and early diagnosis of debilitating disease28. The major providers of exome capture platforms are NimbleGen, Agilent Technologies and Illumina, each having different designs and strengths28.For example, among families studied through an enriched exome capture of a panel of genes involved in neuromuscular diseases, 60% had definitive diagnoses with deleterious mutations in the expected causative genes confirmed in family members. Similar diagnoses were identified in an additional 23% that had novel genotype/phenotype findings requiring functional, clinical, and/or genetic confirmationde novo sequence analysis, which is required for a whole sequence discovery, as exemplified in the current Y chromosome application. Nowadays, an exhaustive and complete cartography of the Y chromosome is only guaranteed by the physical isolation of this chromosome followed by de novo sequence assembly29. Doing so is a complex analysis, mainly because the type of reads obtained typically do not cover all regions of interest for the study in a continuous pattern (‘sequence-coverage gaps’). Moreover, repetitive sequences and copy number sequences complicate the analysis and also prevent a contiguous sequence assembly (‘satellite-associated gaps’). The workflow, economy and read length of NGS technologies have improved, but de novo sequencing analysis has not been developed at the same rate. Although genome sequencing is now routine in many laboratories, translating the raw sequence data of complex and repetitive regions into an accurate and comprehensive bioinformatic assembly remains a formidable challenge29.However, there is still a scarcity of data concerning 30, fluorescence in situ hybridization (FISH)31 and degenerate oligonucleotide-primer PCR (DOP-PCR)32 combined with LCM are already described. The aim of this study was to determine the most effective protocol (in terms of cost and accurate sequence conservation) for the capture and sequence analysis of the Y chromosome. Although the Y chromosome is one of the smallest chromosomes in the human genome with a size around 60 Mb, its sequence remains partly unknown in heterochromatic regions. A better method to genetically characterize changes in the Y chromosome creates a tool that is better suited to help us understand its evolution and the genetic contributions of this variation. Successfully being able to do so is highly valuable for many applications in different scientific fields such as molecular anthropology, forensics and biomedicine. To our knowledge, this is the first comparison of several distinct technologies and protocols for the isolation and whole sequence analysis of the human Y chromosome using NGS methodologies2.There are many current methodologies for collecting populations of whole chromosomes or chromosomal target regions for their subsequent DNA analysis. Although laser capture microdissection (LCM) is generally used to isolate specific cells from fixed tissue sections, it has also been effective in the isolation of living cells for re-culture and isolation of individual chromosomes. Preparation of chromosome paintsAfter conducting the three different Y chromosome isolation processes, physical fragmentation was performed with a sonicator Covaris S2, workflow of all the samples was described in Fig. Bioanalyzer gel plots were performed by dispensing 1 µl of sample in every well of the Bioanalyzer chip. DNA samples were isolated from cell culture following the same protocol (specified in section 4.1.). The following capture protocols are explained below in section “4.2. Flow cytometry capture” , “4.3. Microdissection and image acquisition” (about 200 copies of Y chromosome were captured within the cap and dissolved in 135 µl TE (Tris-EDTA) buffer), and in section “4.4. Magnetic streptavidin-bead capture” (eluted in 160 μl of nuclease free water). They were diluted in 130 µl with Low TE Buffer in the first and second methods and concentrated to 130 µl in the third method. The three samples were sonicated using the shear program detailed in section “4.5.1. DNA Shearing”.versus non-targeted chromosomes was approximately an order of magnitude greater for streptavidin-biotin-based capture compared with the other two methods.After the electrophoresis analysis, we saw that the quality and quantity of capture of the magnetic streptavidin-bead methodology was significantly better than the other processes, as can be seen in Fig. vs. off-target material at this point. Capture specificity and accuracy were independently determined after NGS analysis based on the results of the library sequencing data.This analysis identified the relative capture efficiencies of putative Y chromosomal DNA as provided by the three technologies, but since we did not exactly know whether this was indeed a full Y chromosome we could not determine the ratio of on- We performed 10 cell culture replicates with at least five million cells each per replicate. From each cell culture, we selected one for each of the three capturing methodologies , and finally analyzed twice by NGS on Illumina and SOLID instruments (see details in the Methods section).After the preparation of the libraries, quantifying them and checking their quality, they were performed multiplexed and NGS analysis by NextSeq and SOLID. We obtained the best coverage of Y chromosome reads after capture by streptavidin-biotin bead-based selection. After mapping the reads from DNA sequencing , we found that the most selective methodology was bead-based capture. In contrast, reads generated via Y chromosome capture through flow cytometry capture and LCM were located all over the genome. The read depth of Y chromosome from bead-based capture was significantly higher compared to reads from all other chromosomes.ER is the number of mapped reads in the gene’s exons, EL is the sum of the length of all exons in kilo-bases, and MR is the total number of mapped reads. We adapted the RPKM formula to provide a normalized measure of the number of reads that align with each chromosome based on their size: ER equals the number of mapped read in each chromosome and EL the chromosome length.Alignment quantification reads per kilobase per million: Reads per kilobase per million mapped reads formula (RPKM) is used to quantify gene expression from RNAseq experiments. It facilitates transparent comparison of alignment levels both within and between samples, eliminating the influence of different gene length and sequencing discrepancy on the calculation of gene expression. The formula for RPKM is as follows:Dealing with multi-mapping reads: Multi-Mapping Reads are reads that map in more than one location. This is due to the presence of homologous or repetitive sequences throughout the genome. With the so-called -k1 option, Bowtie2 looks for multiple alignments and reports the best fit. Using -k10 option, Bowtie2 reports up to 10 valid ALNS (Alignments) per read. Multi-mapped reads have a lower MAPQ  value. Finally, we performed several strategies to improve the mapping in this chromosome.The mapping algorithm could not assure the actual origin of the sequence when it maps in different regions, so the quality alignment value is lower than in unique mapped reads. The first strategy was a standard mapping for obtaining a valid alignment for each read and observing low quality reads mapping in the Y chromosome. These events are mainly explained by the high rate of repetitive sequences in the Y chromosome, so alignment parameters were changed to obtain 10 alignments for each read in order to obtain a higher coverage. Details of this methodology confirmed that bead-based capture was indeed the best methodological strategy for capturing Y chromosome. See details in Fig. Raw data (xsq files) were obtained from the SOLiD5500xl sequencer. All raw reads were subjected to quality check, corrected and filtered using the SAET (SOLiD Accuracy Enhancement Tool) module included in the LifeScope™ version 2.5 software. Read alignment was performed with LifeScope using the default settings. Human genome assembly hg38 was used as reference. The number of mapped reads to all chromosomes was computed from bam files with Samtools and normalized with respect to the chromosome length see Fig. .Figure 433.The analysis of the whole Y chromosome genome is relevant for many applications: medicine, molecular anthropology and forensic sciences. It is known that this chromosome is one of the smallest (around 60 Mb) and the majority of the length of this chromosome (95%) is composed of “Non-Recombining Y” sequences33. We have performed a comparative analysis of three different chromosome capture protocols to obtain an excellent tool for a whole analysis of this chromosome. We obtained the best collection results by streptavidin-bead capture (DynabeadsMyOne Streptavidin T1)  . These Yfiler markers are not sufficient to resolve sequence ambiguities in several situations. More detail in Y chromosome genome analysis is therefore needed to improve the most accurate genetic identification of the samples.In molecular anthropological analysis, the Y chromosome is currently by far the most popular marker in genetic genealogy38.Y-STRs analysis is the main tool to determine paternal lineages, haplotype diversity and lineage resolution across populations, in crime cases and kinship analyses, but commercial Y-STRs kits are not suitable for male individual identification because male relatives typically share the same resulting haplotype. This can also be an advantage because the non-recombining nature of male-specific Y chromosome markers allows to solve historical cases of paternity, or other types of paternal kinship dispute, as well as identification cases many generations after they occurred. Doing so is nearly impossible with recombining autosomal DNA. We hope that - aided in part by our findings - future Y-STRs kits may include more markers, particularly more RM Y-STRs . Having a complete sequence of this chromosome available from many individuals is a big step for improving these kits and current male identifications, for better knowledge about the geographic distribution of Y-SNPs, and for improving the geographic resolution of paternal ancestry inference. The identification of human profiles has already been greatly improved by the addition of large numbers of multiplexed Y-STRs, as applied for autosomal STRs, Y-STRs, and SNPs such as the ForenSeq kit 37. Loss of Y chromosome has been found in association with smoking, shorter survival and a higher risk of cancer . It was suggested that LOY (loss of Y chromosome) in blood cells could become a predictive biomarker of male carcinogenesis39, because it is known that the Y chromosome is frequently lost in hematopoietic cells, representing the most common somatic alteration in men and it has a demonstrated role in cancer susceptibility40. So a better knowledge of more Y chromosome sequences will help us develop a deeper understanding between Y chromosome alterations and male cancer development. Mobile Elements (MEs) collectively constitute at least 51% of the human genome. There are formed by repeated sequences which show a large similarity to Y chromosome sequence. So, if we understand how these repeated sequences act in the Y chromosome we can understand better how MEs act in the whole genome. Furthermore, the Y chromosome is a strikingly hot target for human specific MEs, particularly for LTRs, which showed an insertion rate 15 times higher than the genome average41, however previous studies reported controversial data about LINE 1 density and total interspersed repeat elements at Y chromosome42.Men are at a higher risk of developing and dying of sex-nonspecific cancers, but the reasons for this remains unknown. Y chromosome loss and rearrangements have been associated with different types of cancer, such as bladder cancer, male sex cord stromal tumors, lung cancer and esophageal carcinomaTo summarize, the full utilization of the wealth of Y chromosome genetic information has been trapped in uncharted territory to this day due to the inability of collecting and analyzing its whole genome. With the present selection of methodological success in collecting and analyzing Y chromosomes, we can greatly improve the applications of studying this chromosome in multiple scientific areas like forensics, oncology and evolution, among others.43. When the cell count was over 5 million cells per milliliter we processed them to perform the karyotype, adding 63 µl of colcemid (10 µg/ml)  and incubating them for 24 hours at 37 °C. The colcemid allows an accumulation of cells in metaphase43.For achieving a high number of chromosomes, we have performed lymphocytes cell culture collected from peripheral blood in sodium citrate anticoagulant. After being selected by Ficoll protocol we have cultured them using RPMI  1640 medium (4 mL), fetal bovine serum (2 mL), PHA (200 µl)  and Interleukin-2  . For chromosomes extraction, the cells should have a high mitotic index, which is difficult to achieve with primary cultures. For that reason, we increased the rate of mitosis by adding PHAFirst, we perform nucleus disruption by centrifugations and incubations with hypotonic solution, other disruption methods (such as sonication and syringe sample passing) and hypotonic shock by water incubation. After this, we performed a centrifugation (10 min per 200 g) and add to the pellet 1.5 ml of frozen polyamine buffer incubating during 10 min. Finally, we performed a centrifugation for 1 min per 100 g and collected the upper phase that contains chromosomes. At this point we visualized the morphology of chromosomes in a Zeiss Axio Imager A1 epi-fluorescence upright microscope by 4′,6-Diamidino-2-Phenylindole, Dihydrochloride (DAPI) staining.In the case of flow cytometry and magnetic streptavidin–bead capture, after 1 min centrifugation of the sample at 100 g, we collected the upper phase and incubated with 15 µl of the specific biotin Y chromosome probe . Afterwards, the sample with the probe was incubated for 10 min at 80 °C and hybridized 16 h at 37 °C. For flow cytometry capture, streptavidin–biotin hybridization was performed by a centrifugation (453 g for 5 min), adding of staining buffer and streptavidin-phycoerythrin (streptavidin-PE) , followed by incubation (30 min) and wash. Magnetic streptavidin–bead capture samples were directly processed as specified in section (4.4.1) on streptavidin-biotin capture.SRY gene was only found on the Y chromosome which assures the chromosomal specificity of the probes.In the case of LCM we processed the sample with a different protocol. Y chromosome-specific probes XCE Y (centromere) and XCP Y   conjugated with fluorescein isothiocyanate (FITC) were selected because they were the most specific ones to catch several regions of the Y chromosome. They both hybridize in different regions of the Y chromosome (centromere and SRY region) that was essential for performing this assay. The in situ hybridization in suspension) hybridization using specific green probes for Y chromosome regions (10 µl XCP Y and 10 µl XCE Y). FISH-IS was done by several centrifugations (394 g for 5 min) followed by mixing with 200-100 µl of 2 × SSC  and finally, adding 10 µl of both probes and placing the samples in thermocycler (5 min 80 °C and 2 h 37 °C). Samples were subsequently used in the LCM procedure by a use of a previously activated slide with a membrane that retains the stained chromosomes.Finally, we performed a FISH-IS (fluorescence 2O (double-distilled water) for further processing. For data analysis, acquire a total of 10000 events. Flow Cytometry data were acquired with FACSDiva software  and results were analyzed with FACSuite software . To display the data, we did a primary analysis gate set on a dual parameter dot plot comprising forward scatter  versus side scatter . We try to spot the nuclei, since there will invariably be some remaining in the chromosome preparation. Using linear FSC, we can use the nuclei to help guide us to the chromosomes. Simply increase the FSC gain to reveal the chromosomes. Sorting windows were drawn on the fluorescence dot plot of DAPI  versus streptavidin-PE . See details in Fig. The stained chromosome suspension was processed on a fixed-alignment benchtop high-speed cell sorter FACSAria™ equipped with low-powered, air-cooled and solid-state lasers spatially separated at the flow chamber. DAPI was excited with a Point Source Violet Solid State to emit light at 407 nm (nanometers) at 25 mW (milliwatts) laser power. DAPI fluorescence was measured through 450/40 nm band-pass filter. Phycoerythrin was excited with a Coherent Sapphire™ Solid State to emit at 488 nm at 20 mW. Phycoeythrin fluorescence was measured through 585/42 band-pass filter. Configure the FACSAria™ for high speed sorting with optimal setting of the sheath pressure to 70 psi and the drop drive frequency to 90 KHz (kilohertz) using a 70 µm nozzle tip. Select the high purity option of single cell mode. The sample flow rate was 10 µl/min. Sorted chromosomes were collected in Eppendorf tubes in ddHA Zeiss PALM MicroBeam IV Laser Microdissector  equipped with an epi-fluorescence module was used for chromosomes dissection and collection. This system consists of a 355 nm ultraviolet laser that is coupled to the light path of a Zeiss Axio Observer Z1 inverted microscope and focused through a Zeiss LD Plan Neofluar 63x/0.75 NA  Korr M27 objective. The microscope stage and the laser micromanipulation procedure are computer controlled with the PALM Robo software version 4.5.Individual chromosomes hybridized with XCE Y and XCP Y, Y chromosome-specific probes conjugated with fluorescein isothiocyanate (FITC) green dye, counterstained with DAPI and mounted on slides covered by polyethylene membrane  were excited with reflected light of a HBO 100 mercury lamp and visualized with a Zeiss AxioCam ICm1 monochrome camera. In the green channel, only Y chromosomes were selected and catapulted by the laser pressure catapulting (LPC) function, with a single laser pulse and parameter of energy 63.9 µJ/pulse, directly into a Zeiss Adhesive Cap 500 opaque tube. The cap, in a tube holder, was positioned in the centre line of the laser beam above the objective. About 200 copies of Y chromosome were captured within the cap and dissolved in 135 µl TE (Tris-EDTA) buffer . The cap was closed with the remaining tube and the sample was spun down by centrifugation.A Zeiss LSM 710 confocal laser scanning inverted microscope  with Zeiss ZEN 2010 software was used for chromosome imaging. Individual chromosomes hybridized with XCE Y and XCP Y, Y chromosome-specific probes conjugated with FITC (green), and counterstained with DAPI were excited with 3% AOTF  of 405 nm/30 mW diode laser line for detection of DAPI signal and 4% AOTF of 488 nm/25 mW argon laser line for green signal. A Zeiss Plan-Apochromat 63×/1.40 NA oil-immersion DIC  M27 objective and a 2.05 Airy Units pinhole were used for sequential channel acquisition of images. Details are marked in Fig. Bead-based capture procedures were modified from related protocols .After resuspension of the Dynabeads MyOne Streptavidin , 400 µl were divided into 8 low binding plastic tubes, and washed with 200 µl of binding buffer , mixed on a vortex mixer for 5 s before removing the supernatant on a magnetic rack for a total of 3 washes. 15 ml of the sample previously incubated with biotinylated Y chromosome probe was concentrated for 1 h at 30 °C and separated into those 8 tubes with the Dynabeads.The hybrid capture-bead solution was incubated on a rotator device for 80 min at room temperature. The solution was briefly spun in a centrifuge, the beads and buffer were separated on a magnetic rack and the supernatant was removed. The DNA-coated beads were then resuspended in 500 µl of SureSelect Wash 1  by mixing on a vortex mixer for 5 s and briefly spun in a centrifuge, the beads and buffer were separated on a magnetic rack and the supernatant was removed. This step was repeated, incubating for 15 min at room temperature, with two mixes on a vortex mixer . This step was repeated, the solution was incubated for 5 min at room temperature and mixed twice on a vortex mixer. It was briefly spun in a centrifuge, the beads and buffer separated on a magnetic rack and the supernatant removed. Before the beads dried, 20 µl of nuclease-free water were added to every tube and mixed well on a vortex mixer. The samples were incubated for 2 m at room temperature and separated the beads and the supernatant on a magnetic rack. The clear supernatant was transferred from each tube to a low binding plastic tube. The 8 separated samples were pooled together in a Covaris microtube .The three different methods of captured samples were kept at −20 °C until processing for NGS. We performed NGS analysis with two technologies  and SOLID 5500XL System ) following a modified SureSelect XT Target Enrichment System for the preparation of libraries for Illumina Paired-End Multiplexed Sequencing and SOLiD Multiplexed Sequencing.We degassed the samples in a Covaris S2 instrument for 30 min before use, chilled to 5 °C and set up the Covaris S2 for shearing as described in Table We removed the sheared DNA into a low binding plastic tube and kept it on ice. We checked the quality using the 2100 Bioanalyzer System with the Agilent Technologies High Sensitivity DNA Kit. The target peak for base pair size was approximately 150 bp. Both different SureSelect Library Prep Kits  were used for preparing the mixes for enzyme reactions and PCRs.For 100 µl of the sample, we used 11 µl (10X) End Repair Buffer, 1.6 µl dNTP Mix, 1 µl T4 DNA Polymerase, 2 µl Klenow DNA Polymerase and 2.2 µl T4 Polynucleotide Kinase . This mixture was incubated for 30 min at 20 °C on a thermoblock.After maintaining room temperature for at least 30 min, the AMPure XP beads (Agencourt) were mixed thoroughly and 90 µl added to every sample, mixed again on a vortex mixer and incubated for 5 min. On a magnetic rack, the solution became clear and the supernatant was discarded. The sample was washed with two 500 µl of 70% ethanol washes, dried on the 37 °C heat block for 5 min, 15 µl of Nuclease-free Water were added, mixed on a vortex mixer, and incubated for 2 min at room temperature. We then put the tube on the magnetic stand and for 2 min. The supernatant containing the selected DNA was recovered (~15 µl).A mix of 11 µl of nuclease-free water, 5 µl 10X Klenow Polymerase Buffer, 1 µl dATP, 3 µl Exo (–) Klenow  were added to the sample. All were incubated for 30 min at 37 °C on a thermoblock followed by AMPure XP bead-based purification in 15 µl of nuclease-free water.A mix of 15.5 µl of nuclease-free Water, 10 µl 5X T4 DNA Ligase Buffer, 10 µl Diluted SureSelect Adaptor Oligo Mix, 1.5 µl T4 DNA Ligase  were added to the sample. The mix was incubated for 15 min at 20 °C on a thermoblock. Subsequently AMPure XP bead-based purification was carried out in 32 µl of nuclease-free water.We used 6 µl of Nuclease-free Water, 1.25 µl SureSelect Primer, 1.25 µl SureSelect ILM Indexing Pre Capture PCR Reverse Primer, 10 µl 5X Herculase II Rxn Buffer, 0.5 µl 100 mM dNTP Mix, 1 µl Herculase II Fusion DNA Polymerase , added to the sample. The amplification conditions are listed in Table We used 22.5 µl of Nuclease-free Water, 10 µl (5X) Herculase II Rxn, 1 µl Herculase II Fusion DNA Polymerase, 0.5 µl 100 mM dNTP (deoxyribonucleotide triphosphate) Mix, 1 µl SureSelect ILM Indexing Post Capture Forward PCR Primer . Details of amplification conditions in Table The target peak for base pair size was approximately 250 bp Fig. .Figure 7The chromosome Y captured library was quantified using Qubit fluorometric quantitation , taking into account the concentration determined by Bioanalyzer for preparing the appropriate molarity.A dilution at 4000 pM was prepared using a solution of Tris-HCl 10 mM, pH8.5 with 0.1% Tween 20 (Bio-Rad Laboratories). It was run following the NextSeq denaturation and library dilution protocol (Illumina) in a Mid Output v2–150 cycles cartridge (Illumina) at a final concentration of 0.7 pM.In the SOLiD system, once the library preparation is finished, clonal bead populations in microreactors containing template were prepared with PCR reaction components, beads, and primers using an Emulsifier system. 11 µl of a dilution of the template at 2500 pM were amplified in a plastic bag inside the Amplifier tool. After PCR, the templates were denatured and subjected to bead enrichment to separate the beads with extended templates from undesired beads. The template on the selected beads underwent a 3′ modification to allow covalent attachment to the slide.http://www.bioinformatics.babraham.ac.uk/projects/fastqc/) is a quality control tool for high throughput sequence data. It aims to provide a simple way to do quality control checks on raw sequence data and give a quick impression of whether the data has any problems of which to be aware before doing any further analysis.FastQC  was used to trim from the raw data any large poly-N or poly-G sequences and low quality bases from the 5′ or/and 3′ ends, discarding very short reads.The Cutadapt tool  with the parameters -k1–sensitive -q -5 0 -3 0–N 0–L 22–end-to-end. Bowtie2 searches for distinct, valid alignments without mismatches for each read, where the entire read must align without trimming bases in both ends. When Bowtie2 finds a valid alignment, it continues looking for alignments that are nearly as good or better. Only the best alignment found is reported.Each sample was aligned with Bowtie2 (http://hgdownload.cse.ucsc.edu/downloads.html#human). The manipulation of each alignment  was performed by the Samtools utilities (https://github.com/samtools/samtools).The samples were aligned to the last version of the Human Reference Genome GRCh38. The reference genome was downloaded from UCSC (Supplementary Figure 1


Support for more analysis programs has been added over time. Currently, Mega2 converts data from several different genetic data formats  into the specific data requirements for over 40 commonly-used linkage and association analysis programs . Recently, Mega2 has been enhanced to use a SQLite database as an intermediate data representation. Additionally, Mega2 now stores bialleleic genotype data in a highly compressed form, like that of the GenABEL R package and the PLINK binary format. Our new Mega2R package now makes it easy to load Mega2 SQLite databases directly into R as data frames. In addition, Mega2R is memory efficient, keeping its genotype data in a compressed format, portions of which are only expanded when needed. Mega2R has functions that ease the process of applying gene-based tests by looping over genes, efficiently pulling out genotypes for variants within the desired boundaries. We have also created several more functions that illustrate how to use the data frames: these permit one to run the pedgene package to carry out gene-based association tests on family data, to run the SKAT package to carry out gene-based association tests, to output the Mega2R data as a VCF file and related files (for phenotype and family data), and to convert the data frames into GenABEL format. The Mega2R package enhances GenABEL since it supports additional input data formats  not currently supported by GenABEL. The Mega2 program and the Mega2R R package are both open source and are freely available, along with extensive documentation, from The early Mega2 could read input data in only a few formats: LINKAGE format5 and Mega2 format. The Mega2 format allowed you to specify additional information in a more straightforward way, via a simple tabular format, than can be done with LINKAGE format. The earliest versions of Mega2 were written in the C computer language.During an association or linkage analysis project, one may need to analyze the data with several different programs. Unfortunately, it can often be quite difficult to get one’s data in the proper format required by each different computer program. Not only must the data be converted to the proper format, but also the loci must be reordered into the desired order. Writing custom reformatting scripts can be error-prone and very time-consuming. To address these problems, we created Mega26, VCF format7, and IMPUTE2 format11. The volume of genome-wide marker data increased significantly, so Mega2 was extended to support the compression of biallelic genotype data (though still supporting microsatellite and other polymorphic data as non-compressed legacy data). As the volume of genotype data increased, it became slow and tedious to validate the genotype data and generate allele frequency data for each separate analysis that Mega2 was used for. Rather, Mega2 was restructured so that the validation and meta data generation were performed once for a given data set.Over time, Mega2 was upgraded to the C++ computer language and some of the internals were rewritten. Reformatting data for more analysis programs was gradually added to Mega2. The formats for genetic data changed over time, and Mega2 was enhanced to read input data in PLINK formatSQLite table for each C structure and “insert” the C structure data into the table. Mega2 later uses this database, via a menu-driven interface, to provide the data needed for any particular analysis. In addition, the data in the database are inherently inspectable and there are database tools to help to selectively extract data. The data are portable and can be shared on different platforms. Since interfaces for many languages are provided for SQLite, the data are accessible in many languages besides C. Of particular interest is R12 because there is a wealth of existing genetic analysis programs already created, well documented, and available in standard repositories such as TheComprehensive R Archive Network (CRAN) andBioconductor. Also, researchers regularly use R to develop new analysis algorithms because R provides a rich environment for statistical computing with many useful libraries. Indeed, there are are many other R packages that can handle genetic data. For example, VariantAnnotation, seqminer, and SeqArray support efficient processing of VCF/BCF files, while SeqVarTools and GENESIS support association testing and other relevant statistical methods17.Until recently, Mega2 used C language structures to store its intermediate data before analysis. Several alternative strategies were considered to save these data for subsequent reuse without having to recompute, reanalyze, and revalidate the data. The first choice was to dump the raw structure data to disk. Reloading the data is fast but it is much harder to inspect the data for debugging. Also, the internal pointers would have to be relocated to new storage areas. A better solution, for many reasons, was to create a18 to carry out gene-based association tests on family data using selected marker subsets, the Mega2SKAT function to run the SKAT R package19 to carry out gene-based association tests on family data using selected marker subsets, the Mega2VCF function to output the Mega2R data as a VCF file and related files (for phenotype and family data), and the Mega2GenABEL function to convert the data frames into GenABEL R objects20. Typically, these R functions are designed to process a small collection of markers at a time. Our versions process all the markers in a transcript for as many genes as desired. Alternatively, the transcripts can be abstracted to just a table of chromosome/start/end base pair positions. Mega2R eases this process of looping over genes, efficiently pulling out genotypes for variants within the transcript boundaries. In addition to describing the functionality of our Mega2R package, we also provide a Use Case illustrating how to apply it in practice.We describe here our Mega2R package, which makes it easy to load SQLite Mega2 databases directly into R as data frames for further analysis and manipulation. In addition, we document several R functions that illustrate how to use the Mega2R data frames as well as perform useful functions: the Mega2pedgene function to run the pedgene R packageMega2R is an R package which loads a Mega2-created SQLite database of genetic information into R as data frames for further analysis . Parts oMega2R package is available from the CRAN repository, and can be run within the R environment on Windows, Mac OS X, and Linux computers. TheMega2R CRAN page documents package dependencies. To prepare an input database for Mega2R, the C++ program Mega22 is needed; it can be obtained from theUniversity of Pittsburgh site or viaBitBucket.Theread.Mega2DB, reads the tables needed by Mega2R from a Mega2 SQLite database into a collection of data frames. It returns an R environment containing these data frames. Before we discuss the Mega2R package, we must describe one important convention of how the database information is stored and how it is accessed later. The Mega2R R package function,read.Mega2DB to the variable ’seqsimr’, then you could supply the value ’seqsimr’ as the named argument, ’envir’:All Mega2R functions that do not return an environment need to have an environment supplied as an argument; the environment is used to store the data frames that contain the SQLite database. There are two ways to pass the environment to a Mega2R function. If you assigned the result ofshowMega2ENV(envir = seqsimr)           The second choice is a bit of a “hack” but it is very convenient. Every Mega2R function (that does not return an environment) has a named argument, ’envir’, defined to take on the default value ’ENV’, as inshowMega2ENV = function(envir = ENV) { ... }           The code above, assigns the local variable, ’envir’ the default value ’ENV’. Thus, if ’envir’ is not provided in the function call, R will use the default assignment and look up the value of ’ENV’. This “hack” does not handle the case where ‘ENV‘ is defined in an outer frame, not the global environment. In this situation, we search backwards from the calling frame to find the first ‘ENV‘ and use it.locus_table and theallele_table. They both have a locus_link. The link in thelocus_table is hashed and a pointer to the corresponding entry in thelocus_table is stored. When theallele_table is read, the locus_link is looked up, then a pointer is inserted into a new field in the “in memory”locus_table (using the look up pointer) to point to the memory location of theallele_table entry,i.e. thelocus_table in memory will point to theallele_table. These “links” are also very useful in R for performing merges of related tables. For example, in the above case, a merge can produce a table with rows containing both locus and allele data. Similar links are used to associate family data with person data, as well as to associate person data with phenotype data and genotype data.In the current Mega2 design, there are SQLite tables for loci data, marker data, allele data, map data, phenotype data, and genotype data as well as pedigree and person data. For completeness,e.g., the phenotype id) per row to indicate which phenotype’s data is contained in the row becomes more complicated because affection status traits and quantitative traits have different data types and number of values. Instead, the phenotype data for each person is stored as one long raw vector composed of multiple values with 8 bytes of data per value either representing an affection status value or a quantitative value. Similarly, the genotype data are stored as a raw vector with a pair of bytes representing a genotype for non bialleleic markers and a raw compressed bit vector with two bits per genotype for bialleleic markers. Note that the internal compressed genotype vector used by Mega2 is one long vector, while the genotype data written to the database is split into separate vectors for each chromosome. The end of each vector may have 0, 1, 2, or 3 unused bit pairs representing no markers. When reading back in from the database, the Mega2 C++ program reassembles the vectors without these gaps. The R version is not as sophisticated: it reassembles all the chromosome vectors and includes these gaps. It then takes care when referencing the nth marker, to add in the gaps of all the chromosomes that come before the nth marker’s chromosome. Note that reassembling the data with no “virtual markers” would require a lot of bit manipulations in R which would not be terribly efficient; while keeping track of the virtual markers introduced by the gaps is not particularly hard.Most tables are composed of integer, numeric and string data see. The pheread.Mega2DB function to read the database into R data frames within the specified R environment.After using Mega2 to compress and store one’s genetic data in a Mega2 SQLite database, then one can use the Mega2Rlibrary(Mega2R)ENV = read.Mega2DBread.Mega2DB function, the ENV environment will contain a set of data frames ending in “_table”, viz.person_table,locus_table. These contain raw data copied directly from the Mega2 SQLite database .If the verbose flag is true, summary statistics will be printed as the data frames are created. After running theread.Mega2DB function also creates other data frames containing derived information. The functionmkfam is called byread.Mega2DB to create thefam data frame, the equivalent of a PLINK .fam sample information file. It merges the rows from thepedigree_table,person_table, andphenotype_table to make afam data frame. Thepedigree_table has a pedigree_link,person_table has a pedigree_link and person_link, andphenotype_table has a person_link field. These link fields are used by the R ’merge’ function to assemble the data. Later, you may want to prune thefam data frame to restrict the samples processed. For, example you might want to eliminate samples with unknown case/control status. After you prune thefam information, the function,setfam, will set thefam data frame while also appropriately pruning thephenotype_table andunified_genotype_table to contain only those persons left in thefam data frame.Theunified_genotype_table collects all the raw byte vectors from the genotype_table stored in the input SQLite database by chromosome for each person and concatenates them into a new vector for each person. The concatenation can introduce up to three “virtual markers” (as mentioned above) at the end of each chromosome if the number of markers contained is not an exact multiple of 4 (genotypes per byte). Themarker_table contains the offset of the marker genotype data assuming all the markers across all the chromosomes are contiguous. There is an analogous offset column needed for theunified_genotype_table accounting for the “virtual markers” in the gaps; this offset column is computed and added to themarker_table. Themarkers data frame is a subset of themarker_table data containing only the name, chromosome, position, originalmarker_table offset and marker offset into theunified_genotype_table vector.ThesetRanges andsetAnnotations functions. In addition, we want to iterate through multiple ranges as would appear in a set of selected gene transcripts and process the markers. To do this, we process each range of markers by invoking a callback function on the range, markers and related data, via one of theapplyFnToRanges,applyFnToGenes, orapplyFnToMarkers functions.We might have genotype data for thousands of samples and millions of markers in a study, but we are unlikely to have the memory to support the associated genotype matrix in R. The Mega2 genotype data is compressed in the SQLite database and remains compressed in its data frame. Most of the time, we do not need to decompress all of it at once. We typically want to examine the markers on a specific chromosome or in the region of some genes of interest. We only decompress the set of markers we need. The key idea is we want to find the set of markers that lie within some base pair range and process just those markers and then we repeat this for the “next” range. We provide two ways to specify these ranges, via theapplyFnToRanges andapplyFnToGenes functions, to loop over a list of ranges or genes, for each one selecting markers that lie within the region/gene of interest. To do this, one has to have well-defined gene boundaries. By default, Mega2R provides an internal list of the chromosome and base pair ranges for the transcripts defined in the refGene table from the UCSC Genome Browser reference assemblyGRCH37. The list was modified to eliminate multiple records of the same gene with the exact same transcript start and transcript end. The list contains 29,062 records. But there are several reasons that the default ranges may not be to your liking. ThesetRanges function lets you use custom ranges; it has two arguments: a range data frame that specifies at least the chromosome, the start position, end position  of each range, and an index vector of three integers that indicates which columns in the range data frame contain the chromosome, start position and end position. If the range data frame also contains a name column, the index vector should have a final fourth integer that indicates the column containing the name.One of Mega2R’s strengths is its ability, via theapplyFnToRanges function  take an initial argument that is a callback function that is called repeatedly for each transcript that has markers present. They also take a final argument that is an R environment. TheapplyFnToRanges function, with no additional arguments, will iterate through each row of the default Mega2R ranges, determine the markers contained between the start and end and then invoke a callback function. Alternatively,applyFnToRanges may be given a range argument and a selector argument which will cause it to use the ranges supplied rather than the default. These two arguments are the same format as the corresponding arguments provided tosetRanges.TheapplyFnToRanges function requires a callback function of three arguments: the first is a data frame of the markers in the range, the second is a single row from the data frame that defines the range , and the third argument is the R environment that contains all the Mega2R data frames. The callback function can apply whatever analysis is required and it can access the other data frames available in the R environment and even store intermediate results back into the R environment. Typically, the callback function will call eithergetgenotypes orgetgenotypesraw to get a matrix of genotypes values for the markers in the range.ThesetAnnotations, lets you use alternate tables. Mega2R will load the selected tables when you access theapplyFnToGenes function.Mega2R can also load a list of genes and their transcripts from the Bioconductor data annotations: “org.Hs.eg.db”and “TxDb.Hsapiens.UCSC.hg19.knownGene”. The former translates a gene name or alias to the entrez ID of the gene. The latter gives start position, end position, and chromosome for each transcript known for every gene. You might want to use the transcript data from another build that is available in Bioconductor or follow their instructions to make your own mapping. The Mega2R function,applyFnToGenes function specifies a list of genes (via the genes_arg argument) from which to extract the transcripts and the corresponding ranges . Alternatively,applyFnToGenes supports other ways to indicate transcript ranges: on sub-ranges of chromosomes (via the ranges_arg argument), on the entire chromosome (via the chrs_arg argument), or on an arbitrary list of markers (via the markers_args argument). The callback function of three arguments  and a list of ranges is passed toapplyFnToRanges and processed as described above.TheapplyFnToMarkers function is the simplest function that uses the aforementioned callback function. It takes one argument that contains selected rows of themarkers data frame. It then invokes the callback function with the marker argument data frame, a NULL range, and the R environment .Thegetgenotypes andgetgenotypesraw return a matrix of nucleotide pairs or a matrix of encoded integers with a column for each marker and containing a row per sample. Both functions take two arguments: rows of themarkers data frame and an environment. The first argument is usually computed by one of theapplyFnToRanges,applyFnToGenes, orapplyFnToMarkers functions. Themarkers data frame has two offsets that are used internally by the decompression code; it also has a name, chromosome number and position that can be used to identify a marker to the user. The twogetgenotypes functions are dispatches that call Rcpp code. The R code collects genotype and allele data from the R environment’s data frames and passes these data arguments to the Rcpp code; it also calls the proper function for the level of compression: 2 bits or 2 bytes per marker. For each marker specified,getgenotypes returns for each sample a string of the corresponding pair of nucleotides, whilegetgenotypesraw returns for each sample a single integer with the integer for the first allele shifted 16 bits and or’ed to the integer for the second allele.The functionsWe now give a brief overview of several processing functions that Mega2R makes available and that illustrate how to build new functions using Mega2R. A much more detailed example may be found in the “Use Case” section.’pedgene’ R package performs gene-level association tests with disease status for pedigree data18. Mega2R enhances ’pedgene’ via theMega2pedgene function, which automates and eases computation of the ’pedgene’ statistics for all the genes in the genome. TheMega2pedgene function does this by invokingapplyFnToRanges on the specified ranges or callsapplyFnToGenes on gene names. Before running theMega2pedgene function, we first callinit_pedgene rather thanread.Mega2DB; the former uses the functiondbmega2_import to load the Mega2 database. Then it generates a modifiedfam data frame, a kind of family file where the case/control values of 0/1/2 are translated to NA/0/1, as required bypedgene. Thepedgene package requires recoding of the genotypes 1/1, 1/2 (and 2/1), and 2/2 , 131074) to 0, 1, and 2 respectively; plus the alleles must be flipped as needed so that 1 is the major allele. The callback function,DOpedgene, transforms the raw genotype matrix and then it calls thepedgene function with several different marker weights . It returns the p-value of the kernel and burden association statistics for each weight. The results are appended to a data frame in the environment, pedgene_results.TheMega2SKAT function eases the process of applying the region-based association tests that are implemented in the SKAT package22. The SKAT package uses kernel regression approaches to compute association statistics such as the Sequence Kernel Association Test (SKAT) and its optimized version (SKAT-O), both for quantitative and dichotomous traits. TheMega2SKAT function is rather similar toMega2pedgene (above). Theinit_SKAT function behaves very much likeinit_pedgene; in addition, it computes a phenotype data frame. TheMega2SKAT function has the signature:If one has a sample of unrelated individuals, theMega2SKAT = function              f andty specify the formula and phenotype type that are used to invokeSKAT_Null_model. Theskat argument indicates the particular SKAT package function to call and the... arguments are place holders for any additional arguments that the chosenskat function needs.The parameters23 for data storage24. The current version of data format is available fromGitHub25. TheMega2VCF function serves several purposes. It allows VCF format files to be generated for analysis by programs that require VCF input. It shows how to extract data provided in the Mega2R data frames for subsequent analysis by other R packages. Finally, it provides a regression for Mega2R by producing the same files from an SQLite database via R code that Mega2 can produce from the identical database via C++ code. The VCF file and related files created both ways should be the same except for time stamps.The VCF data format was originally defined by the 1000 Genomes ProjectMega2VCF function, you should first call theread.Mega2DB function to load a Mega2 database. A .vcf VCF file is the main output ofMega2VCF; it is created from the genotype matrix, supplemented by columns from thefam table andallele_table table. Besides the .vcf file,Mega2VCF generates several additional complementary files. Below, we indicate the file suffix, the internal function that generates the file, and the file contents are presented inBefore running themkphenotype function is a bit subtle. The database contains a raw vector of 8 bytes times the number of phenotypes (per person). The 8 bytes encode either one double precision float number or two integers depending on the encoding of the trait phenotype in thelocus_table (quantitative or affection status). ThereadBin function is used to convert the raw bytes in each 8 byte vector to the correct form.The code in each function illustrates how to assemble the corresponding data from the Mega2R data frames. TheAnother interesting aspect of the code design is how we compute genotype data for a large numbers of markers without needing large amounts of memory. We build the .vcf file a chunk at a time, where a chunk contains a relatively small number of markers . We generate the genotype matrix for a chunk then append the results for the chunk (of markers) to the .vcf file. Then we get a new chunk and repeat. This looping strategy might prove useful for other situations where the results can be written incrementally, a block of markers at a time.20 package is available in the archive section of CRAN (https://CRAN.R-project.org/package=GenABEL). The GenABEL package provides many functions for genome-wide association analysis and it accepts data in several formats. But Mega2 accepts input in still more formats, notably VCF, PLINK, IMPUTE2 and even Linkage format. ThusMega2GenABEL can be a bridge to easily convert data for GenABEL analysis.The GenABELMega2GenABEL function, you must call theread.Mega2DB function to load your database and you should save the returned environment into ’ENV.’ The function,Mega2GenABEL, returns a gwaa.data-class object for the selected markers. It operates by re-writing the Mega2R data frames into one of the input formats that GenABEL supports; currently, this is PLINK .tped format. This requires a .tped file, a .fam file, and a .phe file; they are stored in a temporary directory. The .tped file looks very much like a VCF .vcf file with entries in each marker’s row for the samples’ genotype data. Mega2GenABEL calls the GenABEL “glue” functions,convert.snp.tped, to process the a .tped file and .fam file into a generic GenABEL “raw” format file, then it converts that raw format file and a phenotype file into a GenABEL gwaa.data-class object via the function,load.gwaa.data, and then it deletes the temporary files.Before running theMega2ENVGenABEL produces the same object asMega2GenABEL. It does not write out any temporary files, but rather converts the Mega2R genotype and related data in memory to a GenABEL gwaa.data-class object. It is mainly written in Rcpp and runs 10 to 20 times faster than theMega2GenABEL function.The functione.g., iterating over gene ranges and getting genotypes from the database). Then we demonstrate one of the extended functions,Mega2pedgene. The other extended functions,Mega2SKAT,Mega2VCF andMega2GenABEL are illustrated in theMega2R package vignette. Further, details of all the Mega2R functions are available in theMega2R manual Finally, the package source can be obtained fromCRAN or it can be obtained via git fromBitbucket.We now show some examples of how to use Mega2R. First, we illustrate the base functionality of the Mega2R package (knitr R package (version 1.20)28.The R code in the examples below was executed during the creation of this document using the29 program, which is available fromSourceForge, to simulate an example dataset. To do this, we started with the first example under the “Prevalence” tab within the “Simulate by Disease status” tab on thetutorial page. This simulation creates 1,380 samples of 500,000 markers on a subrange of chromosome 1. To illustrate the Mega2 and Mega2R operations that follow, we subsampled the data down to 1,380 people and 1,000 polymorphic markers.We used the SeqSIMLA2R. We will assume that you have started an R session in which you type the commands in this Use Case (We used R version 3.5.0).You should first install the package Mega2R.install.packages("Mega2R")Bioconductor. Below we will use ’pedgene’ carry out gene-based association tests, where ’genes’ are defined according to a database containing the boundaries of the gene transcripts. This requires two Bioconductor Annotations databases to be installed. The first line below loads the Bioconductor biocLite loader and the next two lines install two annotation databases. One annotation database provides the gene transcript locations and the other maps gene names to Entrez gene IDs.  Please type in R:source("https://bioconductor.org/biocLite.R")biocLite("TxDb.Hsapiens.UCSC.hg19.knownGene")biocLite("org.Hs.eg.db")The above steps are run once.Use case data. First, you will need to load the Mega2R package. Type:library(Mega2R)The files you will need for this Use Case are provided in the Mega2R package. You need to extract these files to the current directory via this command:dump_mega2rtutorial_data(".")You should see the following files:list.files)##  [1] "MEGA2.BATCH.seqsimr" "MEGA2.BATCH.srdta"   "MEGA2.BATCH.vcf"##  [4] "Mega2r.map"          "Mega2r.map.gz"       "Mega2r.ped"##  [7] "Mega2r.ped.gz"       "seqsimr.db"          "seqsimr.db.gz"## [10] "srdta.db"            "srdta.db.gz"Note: The use of the “mega2” executable in our examples expects the Mega2.BATCH.<name> files to be in the working directory and the latter files expect their data files to be in the working directory. When you are done with these exercises, the “clean” command will remove these files and other temporary files:clean_mega2rtutorial_data(".")Creating a Mega2 database. We have provided files in this package that contain the data from the simulation. These files are in PLINK ped format data:•Mega2r.ped•Mega2r.mapdump_mega2rtutorial_data(“.”) command. You can obtain the Mega2 program fromthe University of Pittsburgh site. Then, you will invoke Mega2 on your data. To make matters simple, we will use a pre-constructed Mega2 batch file to automate the processing by Mega2. To run Mega2 to process and create the ’SQLite’ database ’seqsimr.db’, we issue this command at the Unix prompt from within the directory containing the Use Case example files:If you do not wish to install Mega2 right now, you can skip this database creation step and instead later use the seqsimr.db database that was placed in your directory by themega2 MEGA2.BATCH.seqsimr          Note: The vignette associated with the Mega2R package illustrates what the results of this Mega2 run would look like.Mega2 documentation to better understand the interactive process.If you do not provide the command-line argument giving the name of a BATCH file, Mega2 will proceed to ask a series of interactive questions to collect the information needed to produce a database. In addition, it will create a Mega2.BATCH file, similar to the one we suggested you use. You can look at the “Quick Start” section of theMega2r.ped andMega2r.map, indicate the input is PLINK ped format with parameters, and indicate that Mega2 should produce a database calledseqsimr.db, etc. The MEGA2.BATCH.seqsimr file begins with a rather long comment section indicating the keyword values that may be set and their default values. Towards the end of the file, we set the inputs toInput_Database_Mode=1Input_Format_Type=4Input_Pedigree_File=Mega2r.pedInput_PLINK_Map_File=Mega2r.map...PLINK_Args= --cM --missing-phenotype -9 --trait default...Value_Marker_Compression=1Analysis_Option=Dump...DBfile_name=seqsimr.db...If you wish to use any of the Mega2R functions described here on your own data, you will have to first run “mega2” to convert your data into an ’SQLite’ database.The Mega2R package facilitates reading genetic data from a Mega2-created SQLite database.Reading a Mega2 database After you have created the SQLite database “seqsimr.db”, start up R, load the Mega2R package, then use the functionread.Mega2DB to read a Mega2 database.library(Mega2R)ENV = read.Mega2DBread.Mega2DB emits two lines: one with the number of rows and number of columns of the data frame and the other with the column names of the data frame. Finally, an ’environment’, which contains the data frames, is returned.The first argument should be the path to the database. If ’verbose’ is TRUE, for each data frame created in ’ENV’,Verbose Flag When verbose is set in the initial read.Mega2DB, the value will be remembered. It may be used by any subsequent function. If verbose is TRUE, Mega2R functions will print diagnostic information.Use of an Environment The environment returned is used to store the data frames that contain the ’SQLite’ database. The code above stores the environment in global variable ’ENV’. If the named argument, ’envir’, is not provided in any subsequent Mega2R function call, R will look up the value of ’ENV’ starting at the calling frame and chaining up the call stack to the global environment.Back to more examples. The ’ls(ENV)’ function will show you all the variables in the ’ENV’ environment.  Type:ls(ENV)##  [1] "affectclass_table"      "allele_table"##  [3] "charstar_table"         "chr2int"##  [5] "DBcompress"             "DBMega2Version"##  [7] "dosage"                 "dosageRaw"##  [9] "int_table"              "locus_allele_table"## [11] "locus_table"            "LocusCnt"## [13] "map_table"              "mapnames_table"## [15] "MARKER_SCHEME"          "marker_table"## [17] "markers"                "Mega2R"## [19] "pedigree_brkloop_table" "pedigree_table"## [21] "person_brkloop_table"   "person_table"## [23] "PhenoCnt"               "phenotype_table"## [25] "positionVsName"         "refIndices"## [27] "refRanges"              "traitaff_table"## [29] "txdb"                   "unified_genotype_table"## [31] "verbose"A more informative overview of the database can be had with:showMega2ENV## locus count:   1001; phenotype count:  1; compression: 2 bits## marker count:  1000; sample count:  1380#### genetic and physical maps:##   map name map number## 1      Map          0## 2       BP          1#### Phenotypes:##   Index    Name      Type## 1     1 default affection###### basic tables:##                        rows cols## affectclass_table         1    9## allele_table           2002    5## charstar_table            5    3## int_table                35    3## locus_table            1001    5## map_table              2000    6## mapnames_table            2    6## marker_table           1000    8## pedigree_brkloop_table   20    8## pedigree_table           20    8## person_brkloop_table   1380   11## person_table           1380   11## phenotype_table        1380    4## traitaff_table            1    4#### derived tables:##                        rows cols## fam                    1380    8## markers                1000    5## unified_genotype_table 1380    2Use standard R operations to examine the created data frames Try typing:str$locus_table)## 'data.frame': 1001 obs. of  5 variables:##  $ pId       : int  1 2 3 4 5 6 7 8 9 10 ...##  $ LocusName : chr  "default" "snp1" "snp2" "snp3" ...##  $ Type      : int  2 4 4 4 4 4 4 4 4 4 ...##  $ AlleleCnt : int  2 2 2 2 2 2 2 2 2 2 ...##  $ locus_link: int  0 1 2 3 4 5 6 7 8 9 ...(ENVMega2R provides two ways to compute a function on the genotypes (or markers) in each of the transcripts. These are further illustrated via examples in section about ’pedgene’ below.setRanges    The default ranges contains 29,062 records taken from the UCSC Genome Browser reference assembly GRCH37. We show a bit of the data frame below. Each row contains 5 values: a transcript id, the gene id and three position values: chromosome, start base pair and end base pair.dim$refRanges)## [1] 29062     5##          XX    SYMBOL TXCHROM   TXSTART     TXEND## 1 NM_005286    NPBWR2   chr20  62737182  62738184## 2 NR_026775 LINC00240    chr6  26924771  26991753## 3 NM_007188     ABCB8    chr7 150725509 150744869 setRanges function as shown in the example below. When the index vector contains only three entries, a range name is generated by concatenating the position information and adding it to the range data frame.You may load your own range set instead of the default. You create a data frame that lists, for each range, the chromosome, the start position, and the end position. And you create an integer index vector that indicates which column contains which data. These two become the arguments to theranges = matrix,                      ncol = 3, nrow = 3, byrow = TRUE) setRanges dim(ENV$refRanges)## [1] 3 4 head(ENV$refRanges)##   X1      X2      X3          ChrStartEnd## 1  1 2240000 2245000 chr1:2240000-2245000## 2  1 2245000 2250000 chr1:2245000-2250000## 3  1 3760000 3761000 chr1:3760000-3761000 If you provide an index vector with four entries, the fourth one indicates the column containing the names of the ranges.ranges = matrix,                      ncol = 3, nrow = 4, byrow = TRUE) ranges = data.frame(ranges) ranges$name = LETTERS[1:4] names(ranges) = c setRanges dim(ENV$refRanges)## [1] 4 4 head(ENV$refRanges)##  chr    start      end name## 1  1  2240000  2245000    A## 2  1  2245000  2250000    B## 3  1  3760000  3761000    C## 4  1  3761000  3762000    D applyFnToRanges    The function,applyFnToRanges, goes through each range and finds the markers that fall within the bounds. The first argument of theapplyFnToRanges function is a callback function with three arguments: the markers in range, the selected range entry and the environment. The callback is invoked repeatedly for each transcript range that contains any markers. If there are no markers contained and the ’verbose’ flag is set, a warning will be printed. The callback function builds a genotype matrix for the samples and each marker in the range. If necessary, the environment (’envir’) can be used to store information between successive invocations.For the examples that follow, we use “show” as the callback function, which simply prints, for each range, the range itself, the first three lines of the markers within the range, and the first three lines of the genotype matrix, in that order. It also prints a little banner before each argument. Finally, it does not print the environment argument value; it does not change.show =  function {     print("** Ranges **")     print(r)     print("** Markers **")     print)     print **")     print(head(getgenotypes(m),3))}A simple example is shown below using the ranges value that were most recently set. We see that the range named “A” contains markers in our example data set.ENV$verbose = FALSE     applyFnToRanges(show)## [1] "** Ranges **"##   chr   start     end   name## 1   1 2240000 2245000      A## [1] "** Markers **"##    locus_link  locus_link_fill   MarkerName  chromosome    position## 57         57               57     snp22730           1     2243896## 58         58               58     snp22731           1     2243897## 59         59               59     snp22733           1     2243899## [1] "** Genotypes  **"##             ##  "12" "12" "11" "12" "12" "22" "11" "11"##  "12" "11" "11" "12" "12" "12" "11" "11"##  "11" "12" "11" "11" "11" "11" "11" "11"     applyFnToRanges can also be provided explicit ranges by using the ’ranges_arg’ argument:applyFnToRanges,                           ncol = 4, nrow = 6, byrow = TRUE),                  indices_arg = 1:4)setAnnotations    If you are iterating/selecting via genes, the default transcript database is “TxDb.Hsapiens.UCSC.hg19.knownGene” from Bioconductor; it is stored in the environment as shown below:ENV$txdb ENV$entrezGene## [1] "TxDb.Hsapiens.UCSC.hg19.knownGene"## [1] "org.Hs.eg.db" Of course, you can change this database. Suppose we want to use build “hg18”, we would run:setAnnotations ENV$txdb ENV$entrezGene## [1] "TxDb.Hsapiens.UCSC.hg18.knownGene"## [1] "org.Hs.eg.db" applyFnToGenes    The functionapplyFnToGenes can apply the ’show’ function to the transcripts of a particular gene via the genes_arg argument. For example, here we apply the ’show’ function to transcripts of theCEP104 gene:# Switch back to using build hg19    setAnnotations    applyFnToGenes)#### ’select’ returned 1:1 mapping between keys and columns## ’select’ returned 1:many mapping between keys and columns## [1] "** Ranges **"##   ENTREZID  ALIAS SYMBOL TXID      TXNAME  TXCHROM TXSTRAND  TXSTART   TXEND## 1     9731 CEP104 CEP104 4281  uc001aky.2        1        -  3728645 3773797## [1] "** Markers **"##    locus_link locus_link_fill  MarkerName    chromosome position## 65         65              65    snp24037             1  3762181## 66         66              66    snp24039             1  3762183## 67         67              67    snp24041             1  3762185## [1] "** Genotypes  **"##             ##  "12" "12" "11" "11" "12" "11" "11" "12"##  "22" "11" "12" "22" "11" "22" "22" "11"##  "11" "11" "11" "11" "11" "11" "11" "11"    applyFnToGenes function has several other optional arguments that can request complete chromosomes, (multiple) ranges of base pairs on chromosomes, or collections of markers. All these arguments define ranges that are passed toapplyFnToRanges for evaluation. Note: If thegenes_arg argument is set to the special "gene" string "*", then all transcripts in the Bioconductor database, will be processed.TheapplyFnToGenes,                                         ncol = 3, nrow = 2, byrow = TRUE))## [1] "** Ranges **"##   ENTREZID ALIAS           SYMBOL TXID TXNAME TXCHROM TXSTRAND TXSTART## 1        -     - chr1:5e+06-1e+07    0      -       1        -   5e+06##   TXEND## 1 1e+07## [1] "** Markers **"##    locus_link locus_link_fill MarkerName chromosome position## 73         73              73   snp30480          1  8264348## 74         74              74   snp30484          1  8264352## 75         75              75   snp30487          1  8264355## [1] "** Genotypes  **"##             ##  "11" "11" "11" "11" "11" "11" "11" "11"##  "11" "11" "11" "11" "11" "11" "11" "11"##  "11" "11" "11" "11" "11" "11" "11" "11"## [1] "** Ranges **"##   ENTREZID ALIAS             SYMBOL TXID TXNAME TXCHROM TXSTRAND TXSTART## 2        -     - chr1:1e+07-1.5e+07    0      -       1        -   1e+07##     TXEND## 2 1.5e+07## [1] "** Markers **"##    locus_link locus_link_fill MarkerName chromosome position## 81         81              81   snp34070          1 12812974## 82         82              82   snp34071          1 12812975## 83         83              83   snp34074          1 12812978## [1] "** Genotypes  **"##             ##  "11" "11" "11" "12" "22" "22" "22" "11"##  "11" "11" "11" "11" "12" "12" "12" "11"##  "11" "11" "11" "11" "22" "22" "22" "11"    # apply function "show" to all genotypes at the 'snp1' marker    # NOTE: Since we are using an arbitrary collection of markers, the    # range is not available.    applyFnToGenes    ## [1] "** Ranges **"## NULL## [1] "** Markers **"##   locus_link locus_link_fill MarkerName chromosome position## 1          1               1       snp1          1        2## [1] "** Genotypes  **"##      ##  "11"##  "11"##  "12"    # apply function "show" to all genotypes on chromosomes 24 and 26    # remember our example database is only chr 1    applyFnToGenes)     Encoded Genotypes    The heart of the above two functions is the calculation of the genotype matrix of the samples. We will build the matrix for the first 10 markers. Remember our database has 1,380 samples so we will just show thehead of the matrix.genotype = getgenotypes dim(genotype)## [1] 1380   10 head##               ##  "11" "11" "11" "11" "11" "11" "11" "11" "12" "12"##  "11" "11" "11" "11" "11" "11" "11" "11" "22" "11"##  "12" "11" "11" "11" "11" "11" "11" "11" "22" "11" Raw Genotypes    The functiongetgenotypesraw will be called with the same 10 markers as above. Recall it returns an integer encoding for each genotype. The integer’s high 16 bits are the index for allele 1 and the low 16 bits are the index for allele 2.# two ints in upper/lower half integer representing allele raw = getgenotypesraw dim(raw)## [1] 1380   10 head##                          ##  65537 65537 65537 65537 65537 65537 65537 65537  65538 65538##  65537 65537 65537 65537 65537 65537 65537 65537 131074 65537##  65538 65537 65537 65537 65537 65537 65537 65537 131074 65537raw.allele.representation = cprint)## [1]  65537  65538 131073 131074The example “show” function used above does not compute any statistics; it just shows the data that are available to analyze. To more usefully illustrate how to apply a user-defined statistical test of interest, we construct here a toy example, the “show2” function, which computes Fisher’s exact test for the trait vs marker and shows the p-value.show2 = function {   fn = function(x) {          tryCatch),                   error = function(e) {list}) $p.value }      print(r)# collect genotypes for the set of markers "m"      mm = getgenotypes# apply fisher.test of trait vs marker for each marker      pv = apply      names(pv) = m$MarkerName      print(pv)}applyFnToGenes function to apply Fisher’s exact test to each marker within the CEP104 gene.Now we can use theapplyFnToGenes)## ’select’ returned 1:1 mapping between keys and columns## ’select’ returned 1:many mapping between keys and columns##   ENTREZID   ALIAS  SYMBOL TXID       TXNAME TXCHROM TXSTRAND TXSTART   TXEND## 1     9731  CEP104  CEP104 4281   uc001aky.2       1        - 3728645 3773797##  snp24037   snp24039   snp24041    snp24048  snp24494  snp24499  snp24506## 0.2649470  0.9628246  1.0000000   0.2059075 0.6286297 0.6897829 0.6897829##  snp24507## 0.6286297getgenotypes function in “show2” could be replaced bygetgenotypesraw without changing the calculated p-values.Note: Since Fisher’s test is a function of unique categorical values, theet al.18 to carry out gene-based association tests on family data looping over selected transcripts.Mega2R provides functions that permit one to run the ’pedgene’ function by Schaidread.Mega2DB function as described previously, here we use a specializedinit_pedgene function to read the Mega2 database. This latter function calls a utility function also used byread.Mega2DB. Then it creates, edits, and rewrites the family (.fam) data, storing it in a ’pedgene’-compatible data frame,fam.   Finally,init_pedgene calculates some values that will be used repeatedly and stores them in the environment that is returned.Rather than read the Mega2 SQLite database with theENV = init_pedgene("seqsimr.db")setRanges function to load your own range set instead of the default, as described above.Mega2R has an internal default list of the chromosome and base pair ranges for a number of gene transcripts. These transcripts come from the UCSC Genome Browser reference assembly GRCH37. The list was further modified to eliminate multiple records of the same gene with the exact same transcript start and transcript end. These data contain about 29,000 records. You may use theinit_pedgene function sets the transcript database to “TxDb.Hsapiens.UCSC.hg19.knownGene” and the Entrez gene name mapping database to “org.Hs.eg.db”. If you wish to use different databases to select transcripts by gene name, you must use thesetAnnotations function to load them from Bioconductor, as discussed above.By default, theMega2pedgene examines the first 100 transcripts and prints the results.  For the seqsimr.db database, the first 100 transcripts contain only one transcript with several markers. To make this Use Case run faster, we noticed that the identified transcript appeared at transcript 54; so we will restrictMega2pedgene to a small range of transcripts around 54, viz. 53 through 55.By default, the functionNote: ’verbose’ needs to be TRUE, for the diagnostics to be printed.ENV$verbose=TRUEMega2pedgene(gs=53:55)## tryFn No markers in range:  NM_014705, DOCK4, 7, 111366163, 111846462## tryFn No markers in range:  NM_003759, SLC4A4, 4, 72204769, 72437804## CEP104 snp24037 520 646 214## CEP104 snp24039 940 386 54## CEP104 snp24041 1377 3 0## CEP104 snp24048 860 460 60## CEP104 snp24494 789 501 90## CEP104 snp24499 891 442 47## CEP104 snp24506 891 442 47## CEP104 snp24507 789 501 90##   chr   gene nvariants   start     end sKernel_BT pKernel_BT sBurden_BT## 1   1 CEP104         8 3728644 3773797   31.96998  0.6297541 -0.6496837##   pBurden_BT sKernel_MB pKernel_MB sBurden_MB pBurden_MB sKernel_UW## 1  0.5158965   1184.995  0.5138866  -1.209563  0.2264468   222.8737##   pKernel_UW sBurden_UW pBurden_UW## 1  0.4111136  -1.169488   0.242207You will see some reports of “No markers in range”, because the database only contains markers on a sub range of chromosome 1 whereas the transcripts span the entire genome. Then you will see a listing of a gene name, a marker name, and count of the 1/1, 1/2, and 2/2 genotypes , e.g.,.CEP104 snp24037 520 646 214        ...         DOpedgene.DOpedgene converts the raw genotype representation returned bygetgenotypesraw to the values 0, 1 and 2. Then it runs ’pedgene’. The results are automatically stored in a data frame with columns: chromosome, gene, number of markers and base pair range followed by ’pedgene’ data: kernel and burden, value and p-values, four values for each of three weightings of the markers. These data are saved in the data frame, ’pedgene_results’, in the environment. They are also printed when ’verbose’ is TRUE.The markers, the range used, and the environment are passed to the callback functionNote: The results are always appended to the ’pedgene_results’ data frame. You should truncate it when necessary.Mega2pedgene on all the transcript entries, but it takes a rather long time. You would type:You could runMega2pedgene(gs=1:nrow(ENV$refRanges), envir = ENV)If you run the above test, you will see that genes DISP1 and KIF26B have at least one p-value less than 0.01 and AK5 and STL7 at least one less than 0.03.You may try searching for transcripts of specific genes. Here, the default transcript database is "TxDb.Hsapiens.UCSC.hg19.knownGene" from Bioconductor. Of course you can change it, if you install a new database from Bioconductor, as shown earlier.We leave the command below as an exercise, as it runs a bit slowly. It needs to find all the transcripts for each gene, then to find all the markers between each pair of transcript start/end ranges, then to compute the genotype matrix for these markers, and finally to call the callback function with the appropriate arguments.applyFnToGenes, envir = ENV)But let us run this function for a few genes:# turn off output & reset pedgene_results data frameENV$verbose = FALSEENV$pedgene_results = ENV$pedgene_resultsapplyFnToGenes, envir = ENV)## ’select’ returned 1:1 mapping between keys and columns## ’select’ returned 1:many mapping between keys and columnsprint(ENV$pedgene_results)##   chr  gene nvariants     start       end sKernel_BT  pKernel_BT## 1   1   AK5         4  77747662  78025654   2593.945 0.228311038## 2   1 DISP1         4 222988431 223179337   4559.340 0.004224181##   sBurden_BT pBurden_BT sKernel_MB  pKernel_MB sBurden_MB  pBurden_MB## 1  -1.400928  0.1612355   1899.249 0.062069786  -2.263002 0.023635537## 2   1.446520  0.1480315   5410.868 0.000253584   2.916462 0.003540261##   sKernel_UW pKernel_UW sBurden_UW pBurden_UW## 1   175.4195 0.05101300  -2.290307 0.02200350## 2   277.5080 0.04407319   2.094983 0.03617254Mega2R is a work in progress, and so there are a number of possible improvements that could be made in the future. These include:•unified_genotype_table until the set of chromosomes that are needed can be computed and then only read the required chromosome genotype vectors.defer constructing the•31. famSKAT_RC is another package for family or unrelated gene-based association analysis for a mix of rare variants and common variants.analogously to Mega2SKAT, add support for the R famSKATRC package•e.g., Genomic Data Structure (GDS) format32). This will support conversion to GDS format in both the SNPRelate and the SeqArray data representations15.analogously to Mega2GenABEL, add support for the CoreArray data storage system . But the database (via NULL) and R (via NA) can efficiently represent a missing values, so we will will convert C missing (-99.99) to SQLite (NULL).As with all software projects,All data underlying the results are available as part of the article and no additional source data are required.Mega2RSoftware name:https://CRAN.R-project.org/package=Mega2RSoftware available from:https://bitbucket.org/dweeks/mega2r/BitBucket repository:https://watson.hgen.pitt.edu/register/docs/mega2R.htmlDocumentation page:Operating system(s): Platform independentProgramming language: R, C++Other requirements; R, SQLite libraryhttps://doi.org/10.5281/zenodo.134358733Archived source code (v1.0.4) at the time of publication:License: GNU GPL 2 No changes required.I have read this submission. I believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard. The authors have adequately responded to all of the reviewers' comments. I do not have any further comments to make.I have read this submission. I believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard. For those who perform computational analysis in the fields of statistical genetics, bioinformatics, or population genetics, it is no exaggeration to say that the lion’s share of one’s time is spent formatting data so that it can be input into a specific analysis program. Having worked in statistical genetics for over two decades, this reviewer recalls a time when commonly used linkage programs such as LINKAGE, GENEHUNTER, S.A.G.E., LIPED, SIMWALK2, and others, each had different data input formats. For those format conversion programs that existed, they worked for one or a small number of other programs . Also, the programs were usually lab-specific, in that they were not publically available, or if they were, there was no “accountability”; that is, there was no error checking for the code, nor was there a way to send “bug reports” to the programmer. That all changed when the first version of Mega2 was released. It was the “Rosetta Stone” for researchers who performed computational analyses. Not only did it allow for one to convert from one format to another seamlessly, it performed data error checking, created log files with each run of the program, and critically, it created Unix/Linux shell scripts that greatly simplified analysis runs. The importance of data storage and format conversion has only grown over time. Like the adage states, the only constant in life is change. The genomic data employed for linkage, association, and other computational analyses has grown in complexity and storage requirements. A list of genomic data employed in computational studies, from an approximate chronological standpoint, contains: di-allelic RFLPs, multi-allelic VNTRs, di-allelic SNPs, quantitative copy number variants (CNVs), next generation sequence, and RNA-seq data. As an example of the complexity of statistical methods to analyze these data, a PubMed search using the key terms “next generation sequencing”, “statistical method” and “software” yields over 350 hits. The practice of program-specific formatting continues. Programs like PLINK, MACH, and METAL have their own input formats. While some of the input files (like the pedigree files) may be similar, other files like those that contain chromosome and base-pair position for a given item , may be different. Given the number of statistical methods being employed, that they will most likely have different formats, that error checking is critical, and that data storage for the volumes of data now being generated must be efficient, it is critical that Mega2R be recognized. Mega2 has enjoyed a long-standing tradition as the “gold-standard” program for data format conversion. Because  Dr. Weeks has directed the updating and stability of Mega2 in its various versions, and continues to do so with Mega2R, one can reasonably expect that Mega2R will be widely used, widely cited, and most especially will make the life of computational geneticists much easier.I have read this submission. I believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard. Baron, Stickel, and Weeks present a well-written article describing the newly-developed R package (Mega2R) as an additional tool to the robust Mega2 data-reformatting software. Mega2R helps alleviate problems in handling huge genetic data by allowing the user to specify regions of the genome, genes, or markers that will be included in the analysis. It keeps the genotype data in a compressed format when reading from the Mega2 SQLite database to efficiently overcome the memory restrictions of R. It includes several functions that allow a user to carry out additional association tests, outputs Mega2R data as a VCF file with other related files, converts data frames into GenABEL-compatible format, and enhances GenABEL by supporting additional input data formats. Mega2R is indeed a useful R package for genetic analysis. I enjoyed reading the manuscript since the authors have clearly described what a user can do through Mega2R.Add a schematic diagram of Mega2R showing the different functions and how they interact with the SQLite database. This will visually help readers understand this article.Mega2pedgene function that allows the user to choose between using reference/alternate alleles instead of major/minor alleles? This may allow Mega2R to facilitate analysis involving datasets from different populations.For future enhancements, would it be possible to have aIs the chunk of 1,000 markers at a time in building the VCF file a fixed value? Or will you allow the user to select a particular number in the future?Indicate the format of the genotype matrix, e.g., normal format , based on your examples.Will Mega2R be back compatible or will it only be compatible with R 3.5.0 onwards?Typographical error (retruns) I have a few minor comments and suggestions below:I have read this submission. I believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard. Thank you for your thoughtful comments and suggestions for strengthening our paper.In Version 2, as suggested, we have added two Figures, in the 'Implementation' section, which now provide graphically illustrate how Mega2 and Mega2R work together  and how Mega2R provides an efficient and flexible wrapper for iterating through gene regions .  However, this does not directly address your request for a diagram showing how the different Mega2R functions interact with the SQLite database.  We did not add such a diagram because the interaction is minimal – at the beginning, we load the SQLite Mega2 databases directly into R as data frames for further analysis and manipulation.  After this step, the functions use the loaded data frames. Regarding your numbered comments, we respond here:1. Using reference/alternate alleles within Mega2R instead of major/minor alleles is not yet possible, but this would definitely be a useful future enhancement.2. Currently Mega2R's chunk size is defined by an internal parameter, so altering the chunk size could be accomplished by altering the source code.  Making this a parameter would also be a useful future enhancement.3. The genotype matrix has individuals in rows and markers in columns. This was indicated in the paragraph that first introduces the getgenotypes and getgenotypesraw functions: "The functions getgenotypes and getgenotypesraw return a matrix of nucleotide pairs or a matrix of encoded integers with a column for each marker and containing a row per sample."  As suggested, in this revision we have added a comment to the 'show' function clarifying this later in the manuscript.4. Due to constraints encountered when submitted the Mega2R package to CRAN, Mega2R requires an R version of 3.5.0 or higher.  As version 3.5.0 was released some time ago, in April 2018, hopefully this version requirement is not a burden.5. The typographical error (retruns) has been corrected. Weeks and colleagues described a very useful R package to access multiple data formats and facilitate its integration with R packages. This package is based upon its predecessor MEGA2, which is highly cited and used in genetic data analysis.  This tools is long overdue. While numerous statistical genetics methods are being developed, only a minority of them have really a usable interface. Due to the metadata that modern genetic datasets needs= to store, many of the files are not stored in a rectangular format. Parsing these files and making them analyzable in R is often the most time-consuming part to code but is the key for the development. The package filled in this gap and make easy the development of useful softwares.  I only have a few minor comments:  1) The software is unique and useful, but the existence of other packages that can read and parse genetic datasets in R should be acknowledged. For example, VariantAnnotation package in bioconductor and seqminer in CRAN can both randomly access tabix indexed VCF/BCF files.  2) One of the major strength of the package is to facilitate statistical genetics method development. So it would be helpful if the authors could give a toy example on how to make use of applyFnToGenes to handle a user defined statistical tests.I have read this submission. I believe that I have an appropriate level of expertise to confirm that it is of an acceptable scientific standard. Thank you for your helpful suggestions for improving our paper. In Version 2, as suggested, we now cite, in the Introduction, other R and Bioconductor packages that can read and parse genetic datasets. As suggested, we have added, to the Use Case section, a toy example illustrating how to use applyFnToGenes to apply a user-defined statistical test.