Introduction
This package has six main functionalities: (1) reading in and writing out VCF data files, including precalculation of diverse metrics used in the filtering functions; (2) data filtering functions; (3) merging VCFs; (4) subsetting VCFs; (5) generation of summary statistics and graphs; and (6) data transformation and writing out of other data formats (population genetic and phylogenetic formats) for downstream analyses. It has been designed to be fast, implementing shared, C++ backed APIs and functions, which have been parallelized when possible, and memory efficient, implementing the lazy-loaded Apache Arrow data scheme. This package is, therefore, capable of processing VCFs comprising tens of millions of SNVs and hundreds of individuals in a matter of seconds to minutes with minimal RAM overhead.
How to use the functions of this package
Following are examples of the usage of the functions of this package.
Parallel processing (optional)
VCFArrow stores the genotypes on disk in chunks of variants, and most
functions process one chunk at a time. vcf_set_workers()
starts a number of background R processes (workers) and from then on
distributes the chunks over them, so that several chunks are processed
at the same time. This applies to read_vcf(), the
genotype-based filters, sample and group extraction,
vcf_stats() and vcf_theta(), the assess
functions, vcf_bind(), write_vcf(), the
vcf2*() exporters and vcf2gt_long() with CSV
output. Functions that only use the variant table (for example the
quality, PASS, biallelic or indel filters) are fast and always run in
the main session.
# process chunks on 4 background R processes
vcf_set_workers(workers = 4)
# ... read, filter, compute statistics and export as usual ...
# stop the workers and return to processing in the main session
vcf_set_workers(1)The workers are started once and reused by every following call until
vcf_set_workers(1) is called or the R session ends. Results
do not depend on the number of workers. Each worker is a separate R
process that holds about 1 GB of memory, so memory use grows with the
number of workers. Workers pay off for large datasets: on 18.6 million
variants by 56 samples, most functions ran about twice as fast with 4
workers, while more workers than that brought little further gain
because reading and writing the disk becomes the limit. For small
datasets such as the one in this tutorial, starting the workers costs
more time than they save, so the code above is not run here.
Load VCF and associated files of individuals and groups
First we need to read in the VCF. If one has information on the grouping of individuals, this information can also be put into the VCFArrow object. This grouping information is stored in a ‘strata’ file (a text file with a header line and at least two columns, ‘id’ and ‘pop’, separated by tabs or by spaces; with tabs, names may contain spaces). Samples not listed in the file get no group (NA), with a warning. The grouping of individuals can be used in filtering steps, and it is necessary for transformation of the VCFArrow object to other population genetic formats, many of which require it.
The data used in this example are from (Mota et al., 2026)—a population genomic analysis of the Phyllomedusa vaillantii species complex. The original dataset has 18579683 SNVs by 56 samples. For the purpose of this tutorial, the dataset was randomly subsampled to 10000 SNVs by 18 samples (five samples by three main lineages of Phyllomedusa vaillantii as ingroups, plus three samples of Phyllomedusa bicolor included as outgroups).

library(VCFArrow)
library(dplyr)
# set path to example files and project name
data_path <- system.file("extdata", package="VCFArrow")
project <- "vaillantii_"
postfix <- "discosnp_sub"
# load vcf and assign individuals to groups based on 'strata'
vcf <- read_vcf(file.path(data_path, paste0(project, postfix, ".vcf.gz"))) |>
set_vcf_groups(data_path)
# visualize the VCFArrow object
vcf
#>
#> An object of class "VCFArrow"
#>
#> Dimensions:
#> Variants: 10000
#> Samples: 18
#>
#> Variant types:
#> Biallelic SNVs: 9313
#> Multiallelic: 0
#> Indels: 687
#>
#> Groups: 4
#>
#> BS GS OG WA
#> 5 5 3 5
#>
#> Genotypes (first chunk with variants): 180000
#> Missing: 47.09%
#> Phased: 45612
#>
#> Storage:
#> Path: /tmp/RtmpCPU1t0/arrow_vcf_216b6d953a16
#> Genotype chunk files: 1
#>
#> Variants (first 5 rows):
#> CHROM POS ID REF ALT QUAL FILTER Rk RPT n_alt
#> 1 SNP_higher_path_9994239 41 9994239_1 C G . . 1 NA 1
#> 2 SNP_higher_path_9984432 105 9984432 C T . . 1 NA 1
#> 3 SNP_higher_path_9967574 50 9967574 A C . . 1 NA 1
#> 4 SNP_higher_path_993510 88 993510_4 A G . . 1 NA 1
#> 5 SNP_higher_path_9803974 33 9803974 A G . . 1 NA 1
#> is_biallelic is_indel .row_id
#> 1 TRUE FALSE 1
#> 2 TRUE FALSE 2
#> 3 TRUE FALSE 3
#> 4 TRUE FALSE 4
#> 5 TRUE FALSE 5
#> ... 9995 more
#>
#> INFO (first 5):
#> [1] "Ty=SNP;Rk=1.0;UL=11;UR=8;CL=11;CR=27;Genome=.;Sd=.;Cluster=20022615;ClSize=3"
#> [2] "Ty=SNP;Rk=1.0;UL=3;UR=1;CL=75;CR=7;Genome=.;Sd=.;Cluster=17296599;ClSize=1"
#> [3] "Ty=SNP;Rk=1.0;UL=20;UR=4;CL=20;CR=4;Genome=.;Sd=.;Cluster=18266172;ClSize=3"
#> [4] "Ty=SNP;Rk=1.0;UL=1;UR=0;CL=1;CR=0;Genome=.;Sd=.;Cluster=16400006;ClSize=2"
#> [5] "Ty=SNP;Rk=1.0;UL=3;UR=7;CL=3;CR=7;Genome=.;Sd=.;Cluster=10880986;ClSize=5"
#>
#> FORMAT (first 5):
#> .row_id FORMAT
#> 1 GT:DP:PL:AD:HQ
#> 2 GT:DP:PL:AD:HQ
#> 3 GT:DP:PL:AD:HQ
#> 4 GT:DP:PL:AD:HQ
#> 5 GT:DP:PL:AD:HQ
#>
#> Samples (first 5):
#> [1] "Pv120" "Pv126" "Pv13" "Pv14" "Pv27"
#> ... 13 moreSamples can be renamed with rename_vcf_samples(), from a
named vector (c(old = "new")), a data frame or a file with
the columns ‘id’ (current name) and ‘new_id’ (new name). By default each
sample keeps its group; with update_groups = TRUE the
groups are taken from a ‘pop’ column. Renaming creates a new object, as
the sample names are stored with the genotypes; the object
vcf used in the rest of this tutorial keeps the original
names.
# rename two samples, keeping their groups
vcf_renamed <- rename_vcf_samples(vcf, c(Pv120 = "WA_Pv120", Pv13 = "WA_Pv13"))
#> ℹ Renamed 2 samples; group assignments kept.
head(vcf_renamed@samples)
#> [1] "WA_Pv120" "Pv126" "WA_Pv13" "Pv14" "Pv27" "Pv28"Assessment of missing data
The function assess_vcf_missing_data() is used to
generate a table and graph of missing data for each sample in a VCFArrow
object, while the assess_vcf_coverage() generates a violin
plot of read depths of each sample. Both are useful for visualizing data
before and after filtering to evaluate the effect of filtering. The
functions accept parameters which form part of the name of the output
file. The idea is that the output file name contains information on the
name of the project (project), how the VCF was extracted (postfix), and
how it was filtered (fltr). The ‘postfix’ and ‘fltr’ can be left blank
if the VCF name does not contain this information. Samples are ordered
and colored by group assignment. The ‘details’ flag specifies whether or
not filtering information is presented in the figure or if only the
species name is reported. The default is to report species name and
details.
# define results path
res_path <- tempdir()
# species for plot title
species <- "Phyllomedusa vaillantii"
# filter - filter parameters in file name
fltr <- ""
# output a table and histogram of missing data
assess_vcf_missing_data(vcf, res_path, species, paste0(project, postfix, fltr))
# output a violin plot of read depth/coverage
assess_vcf_coverage(vcf, res_path, species, paste0(project, postfix, fltr))Basic stats for individuals in VCF
The function vcf_stats() is used to generate a table
with basic stats for each sample in the VCFArrow object. These stats
include per sample average read depth, heterozygosity, number of
heterozygotes, homozygotes, REF homozygotes and ALT homozygotes, percent
missing SNVs, total missing SNVs, total non-missing SNVs and total SNVs,
the inbreeding coefficient F (with the numbers of sites and of observed
and expected homozygotes it is based on, and the mean F of the sample’s
group), Watterson’s Theta and Pi for the entire dataset, and per group
Watterson’s Theta and Pi, plus the number of individuals in each group.
F is the method-of-moments estimate of vcftools and PLINK; by default
the expected homozygosity uses the allelic frequencies of all samples
(f_ref = "all"), and with f_ref = "group"
those of each sample’s own group, which avoids inflating F when groups
differ in allelic frequencies. The calculation of Watterson’s Theta and
Pi can be included or excluded based on the ‘theta’ flag.
Filtering, subsetting, merging and otherwise wrangling VCF files
Most but not all functions can be used by the user directly on the
VCFArrow object. Internally, all filters use two common
functions, .vcf_filter_rows() for variants and
.vcf_filter_columns() for samples, which are not exported.
Other functions, such as vcf_filter_invariant() will remove
invariant SNVs from a VCFArrow object; however, VCF by definition should
not have invariant SNVs. So this function is primarily called by other
functions to remove loci that may have become invariant following
filtering.
Subsetting samples and variants
There are two types of subsetting functions. The first type is used
to subset the VCFArrow object by specific samples
vcf_extract_samples() or groups (all samples of a group) of
samples vcf_extract_groups(). The ‘keep’ flag in both
functions determines whether the indicated samples should be extracted
from the VCF (‘keep = TRUE’) or excluded from the VCF (‘keep = FALSE’).
Once subsetted, the invariant SNVs are removed by default, however, this
behavior is controlled by the ‘f_invar’ flag. The second type subsets a
random number of SNVs from the VCF. The subsetting is done either across
the entire VCF vcf_sub_SNVs() or proportionately within
each chromosome/linkage group vcf_sub_SNVs_stratified().
For repeatability, both functions accept a ‘seed’; if ‘seed’ is not
specified, it is randomly generated.
# subset VCF by individuals (default keep = TRUE, remove invariants f_invar = TRUE)
indivs1 <- c("Pv14", "Pv27", "Pv28", "Pv78", "Pv126")
vcf1 <- vcf_extract_samples(vcf, indivs1)
#> ℹ Compacting GT: 18 -> 5 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 3352 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pv120, Pv13, Pv2, Pv31, Pv56, Pv62, Pv68, Pv73, Pv79, Pv93, Pb2Jp, Pb2Scx, and Pb1Rd
#> ℹ Variants retained: 3352 | Samples retained: 5 | Missing data: 22.04%
# see how many variants remained
nrow(vcf1@variants)
#> [1] 3352
# subset VCF by groups (default keep = TRUE, remove invariants f_invar = TRUE)
groups1 <- c("GS", "BS", "WA")
vcf1 <- vcf_extract_groups(vcf, groups1)
#> ℹ Compacting GT: 18 -> 15 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 8421 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pb2Jp, Pb2Scx, and Pb1Rd
#> ℹ Variants retained: 8421 | Samples retained: 15 | Missing data: 40.00%
# see how many variants remained
nrow(vcf1@variants)
#> [1] 8421
# subset VCF by a random number of variants (default n_SNVs = 10000)
vcf1 <- vcf_sub_SNVs(vcf, n_SNVs = 5000)
# see how many variants remained
nrow(vcf1@variants)
#> [1] 5000
# subset VCF by a random number of variants proportional to chromosome length (default n_SNVs = 10000)
# should be used when SNVs are mapped to chromosomes or scaffolds
vcf1 <- vcf_sub_SNVs_stratified(vcf, n_SNVs = 5000)
# see how many variants remained
nrow(vcf1@variants)
#> [1] 5000Filtering
Filtering consists of removing samples and variants based on specific
properties. The function vcf_filter_missing() is the only
function that filters samples based on % missing SNV threshold. The
other functions filter on properties of individual SNVs across samples.
The function vcf_filter_missingness() removes SNVs above a
% missing threshold, vcf_filter_quality() removes SNVs
below a quality threshold, vcf_filter_pass() removes SNVs
that did not PASS filters, vcf_filter_maf() removes SNVs
with minor allele frequency below a % threshold,
vcf_filter_hets() removes SNVs with heterozygosity above a
% threshold, vcf_filter_rank() removes SNVs with rank below
a % threshold (rank is specific to VCFs generated by DiscoSnpRad and
measures the likelihood of observed SNV variation being due to
paralogs), vcf_filter_rpt() removes SNVs with a repeat
score above a threshold (repeat is also specific to DiscoSnpRad VCFs;
high values indicate paralogs), vcf_filter_paralogs()
applies both the rank and the repeat filter,
vcf_filter_adr() either removes (make genotype missing) or
corrects (make genotype homozygous) genotypes with allele ratio
imbalance, vcf_filter_coverage() sets genotypes with a read
depth (DP) below a threshold to missing (default
strict = TRUE), or with strict = FALSE leaves
the genotypes unchanged and removes SNVs with fewer than two polymorphic
genotypes at or above the threshold, and
vcf_filter_biallelic() removes all variants that are not
biallelic. Finally the vcf_filter_invariant() removes
invariant SNVs (SNVs may become invariant after subsetting and
filtering); by default a SNV is invariant if all its alleles are the
same, and with strict_poly = TRUE if all its genotypes are
the same, which also removes SNVs where every sample is heterozygous.
The function vcf_filter_indels() removes indels from the
VCF, retaining only SNVs. The functions vcf_filter_oneSNV()
and vcf_filter_multiSNV() filter the VCF to remove linked
SNVs (retain only unlinked SNVs) or retain only linked SNVs,
respectively. In general, all analyses assume that SNVs are unlinked,
however, some analyses such as FineRadStructure work with linked
SNVs.
# filter VCF for analyses (unlinked SNVs)
vcf_oneSNV <- vcf |>
vcf_filter_indels() |>
vcf_filter_biallelic() |>
vcf_filter_maf(.03) |>
vcf_filter_coverage(10) |>
vcf_filter_missingness(.2) |>
vcf_filter_missing(.3) |>
vcf_filter_invariant() |>
vcf_filter_oneSNV()
#> ℹ Applying indel filter
#> ℹ Retained 9313 / 10000 variants (non-Indels)
#> ℹ Applying biallelic filter
#> ℹ Retained 9313 / 9313 variants (biallelic variants)
#> ℹ Applying MAF filter
#> ℹ Retained 9069 / 9313 variants (MAF >= 0.03)
#> ℹ Applying read coverage filter
#> ℹ Set 32198 / 84246 called genotypes with DP < 10 to missing
#> ℹ Applying locus missingness filter
#> ℹ Retained 910 / 9069 variants (per-variant missingness <= 0.2) | Missing data: 8.02%
#> ℹ Applying sample missingness filter
#> ℹ Variants retained: 910 | Samples retained: 18 | Missing data: 8.02%
#> ℹ Applying invariant filter
#> ℹ Retained 899 / 910 variants (polymorphic at the allele level)
#> ℹ Applying unlinked SNV filter
#> ℹ Retained 899 / 899 variants (unlinked SNVs)
# see how many variants remained
nrow(vcf_oneSNV@variants)
#> [1] 899
# filter VCF for analyses (linked SNVs)
vcf_multiSNV <- vcf |>
vcf_filter_indels() |>
vcf_filter_biallelic() |>
vcf_filter_maf(.03) |>
vcf_filter_coverage(10) |>
vcf_filter_missingness(.2) |>
vcf_filter_missing(.3) |>
vcf_filter_invariant() |>
vcf_filter_multiSNV()
#> ℹ Applying indel filter
#> ℹ Retained 9313 / 10000 variants (non-Indels)
#> ℹ Applying biallelic filter
#> ℹ Retained 9313 / 9313 variants (biallelic variants)
#> ℹ Applying MAF filter
#> ℹ Retained 9069 / 9313 variants (MAF >= 0.03)
#> ℹ Applying read coverage filter
#> ℹ Set 32198 / 84246 called genotypes with DP < 10 to missing
#> ℹ Applying locus missingness filter
#> ℹ Retained 910 / 9069 variants (per-variant missingness <= 0.2) | Missing data: 8.02%
#> ℹ Applying sample missingness filter
#> ℹ Variants retained: 910 | Samples retained: 18 | Missing data: 8.02%
#> ℹ Applying invariant filter
#> ℹ Retained 899 / 910 variants (polymorphic at the allele level)
#> ℹ Applying linked SNV filter
#> ℹ Retained 0 / 899 variants (linked SNVs)
#> ℹ 0 blocks with more than 5 SNVs removed
# see how many variants remained
nrow(vcf_multiSNV@variants)
#> [1] 0No linked SNVs remain here because of how the tutorial dataset was
made. It is a random sample of 10000 of the 18579683 SNVs, and with
DiscoSnpRad data, where nearly every locus is its own CHROM, a random
sample of SNVs rarely includes two from the same locus: only four loci
have two SNVs, and none of these pairs survives the filters.
vcf_filter_multiSNV() therefore retains no SNVs, and the
fineRADstructure file written below contains no loci. With the complete
dataset, in which loci can have several SNVs, the same pipeline retains
the linked SNVs that pass the filters.
Extracting and binding
The functions vcf_bind(),
vcf_extract_samples() and vcf_extract_groups()
are used to bind two or more VCFArrow objects, and to extract
samples/groups of samples from a VCFArrow object, storing them in a
separate VCFArrow object. Variants are matched by CHROM,
POS, REF and ALT, so the objects
can also come from different VCF files, for example from separate
sequencing runs.
Matching requires each locus to be described the same way in every
dataset. This is assured when all datasets were called against the same
reference genome assembly, which gives the same CHROM,
POS and REF for the same locus. It is
generally not possible for de novo (reference-free) SNV calling, where
locus names and positions are generated anew in each calling run, so the
same locus will usually not match between separately called datasets;
such datasets should be called together in a single run instead.
Multi-allelic sites can list their ALT alleles in a
different order in different files, so it is best to normalize the VCFs
first, for example by splitting multi-allelic sites with
bcftools norm -m -any.
Extracting individuals - keeping all loci; binding
# extract individuals from VCFArrow object (keep all loci)
indivs1 <- c("Pb2Jp", "Pb2Scx", "Pb1Rd") # the outgroup
vcf_ingrp <- vcf_extract_samples(vcf, indivs1, keep = FALSE, f_invar = FALSE)
#> ℹ Compacting GT: 18 -> 15 samples across 1 chunk
#> ℹ Removed samples: Pb2Jp, Pb2Scx, and Pb1Rd
#> ℹ Variants retained: 10000 | Samples retained: 15 | Missing data: 44.06%
# see how many variants remained
nrow(vcf_ingrp@variants)
#> [1] 10000
vcf_outgrp <- vcf_extract_samples(vcf, indivs1, f_invar = FALSE)
#> ℹ Compacting GT: 18 -> 3 samples across 1 chunk
#> ℹ Removed samples: Pv120, Pv126, Pv13, Pv14, Pv27, Pv28, Pv2, Pv31, Pv56, Pv62, Pv68, Pv73, Pv78, Pv79, and Pv93
#> ℹ Variants retained: 10000 | Samples retained: 3 | Missing data: 62.22%
# see how many variants remained
nrow(vcf_outgrp@variants)
#> [1] 10000
# bind vcf_outgrp and vcf_ingrp (same variants)
vcf1 <- vcf_bind(vcf_ingrp, vcf_outgrp)
#> ℹ Binding 2 VCFArrow objects (intersect): 10000 variants, 18 total samples.
# see how many variants remained
nrow(vcf1@variants)
#> [1] 10000Extracting groups - keeping all loci; binding
# extract groups of individuals from VCFArrow object (keep all loci)
groups1 <- c("GS", "BS", "WA") # the ingroup
vcf_ingrp <- vcf_extract_groups(vcf, groups1, f_invar = FALSE)
#> ℹ Compacting GT: 18 -> 15 samples across 1 chunk
#> ℹ Removed samples: Pb2Jp, Pb2Scx, and Pb1Rd
#> ℹ Variants retained: 10000 | Samples retained: 15 | Missing data: 44.06%
# see how many variants remained
nrow(vcf_ingrp@variants)
#> [1] 10000
vcf_outgrp <- vcf_extract_groups(vcf, groups1, keep = FALSE, f_invar = FALSE)
#> ℹ Compacting GT: 18 -> 3 samples across 1 chunk
#> ℹ Removed samples: Pv120, Pv126, Pv13, Pv14, Pv27, Pv28, Pv2, Pv31, Pv56, Pv62, Pv68, Pv73, Pv78, Pv79, and Pv93
#> ℹ Variants retained: 10000 | Samples retained: 3 | Missing data: 62.22%
# see how many variants remained
nrow(vcf_outgrp@variants)
#> [1] 10000
# bind vcf_outgrp and vcf_ingrp (same variants)
vcf1 <- vcf_bind(vcf_ingrp, vcf_outgrp)
#> ℹ Binding 2 VCFArrow objects (intersect): 10000 variants, 18 total samples.
# see how many variants remained
nrow(vcf1@variants)
#> [1] 10000Extracting groups - remove invariant loci; binding - intersection
# extract groups of individuals from VCFArrow object (remove invariant loci)
groups1 <- c("GS", "BS", "WA") # the ingroup
vcf_ingrp <- vcf_extract_groups(vcf, groups1)
#> ℹ Compacting GT: 18 -> 15 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 8421 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pb2Jp, Pb2Scx, and Pb1Rd
#> ℹ Variants retained: 8421 | Samples retained: 15 | Missing data: 40.00%
# see how many variants remained
nrow(vcf_ingrp@variants)
#> [1] 8421
vcf_outgrp <- vcf_extract_groups(vcf, groups1, keep = FALSE)
#> ℹ Compacting GT: 18 -> 3 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 1559 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pv120, Pv126, Pv13, Pv14, Pv27, Pv28, Pv2, Pv31, Pv56, Pv62, Pv68, Pv73, Pv78, Pv79, and Pv93
#> ℹ Variants retained: 1559 | Samples retained: 3 | Missing data: 13.53%
# see how many variants remained
nrow(vcf_outgrp@variants)
#> [1] 1559
# bind vcf_outgrp and vcf_ingrp (intersection - variable SNVs in all objects)
vcf1 <- vcf_bind(vcf_ingrp, vcf_outgrp, mode = "intersect")
#> ℹ Binding 2 VCFArrow objects (intersect): 765 variants, 18 total samples.
# see how many variants remained
nrow(vcf1@variants)
#> [1] 765Extracting groups - remove invariant loci; binding - union & missing genotypes
# extract groups of individuals from VCFArrow object (remove invariant loci)
groups1 <- c("GS", "BS", "WA") # the ingroup
vcf_ingrp <- vcf_extract_groups(vcf, groups1)
#> ℹ Compacting GT: 18 -> 15 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 8421 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pb2Jp, Pb2Scx, and Pb1Rd
#> ℹ Variants retained: 8421 | Samples retained: 15 | Missing data: 40.00%
# see how many variants remained
nrow(vcf_ingrp@variants)
#> [1] 8421
vcf_outgrp <- vcf_extract_groups(vcf, groups1, keep = FALSE)
#> ℹ Compacting GT: 18 -> 3 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 1559 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pv120, Pv126, Pv13, Pv14, Pv27, Pv28, Pv2, Pv31, Pv56, Pv62, Pv68, Pv73, Pv78, Pv79, and Pv93
#> ℹ Variants retained: 1559 | Samples retained: 3 | Missing data: 13.53%
# see how many variants remained
nrow(vcf_outgrp@variants)
#> [1] 1559
# bind vcf_outgrp and vcf_ingrp (union - variable SNVs in any object)
vcf1 <- vcf_bind(vcf_ingrp, vcf_outgrp, mode = "union")
#> Warning: `absent_as` not specified for `mode = "union"` - defaulting to "missing" (./.)
#> for genotypes absent from a source object.
#> ℹ Set `absent_as = "hom_ref"` explicitly if absent positions represent
#> homozygous-reference calls (e.g. independently called VCFs against the same
#> reference).
#> ℹ Binding 2 VCFArrow objects (union): 10000 variants, 18 total samples.
#> ℹ Absent genotypes will be filled as: missing
# see how many variants remained
nrow(vcf1@variants)
#> [1] 10000Extracting groups - remove invariant loci; binding - union & recover genotypes
groups1 <- c("GS", "BS", "WA") # the ingroup
vcf_ingrp <- vcf_extract_groups(vcf, groups1)
#> ℹ Compacting GT: 18 -> 15 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 8421 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pb2Jp, Pb2Scx, and Pb1Rd
#> ℹ Variants retained: 8421 | Samples retained: 15 | Missing data: 40.00%
# see how many variants remained
nrow(vcf_ingrp@variants)
#> [1] 8421
vcf_outgrp <- vcf_extract_groups(vcf, groups1, keep = FALSE)
#> ℹ Compacting GT: 18 -> 3 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 1559 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pv120, Pv126, Pv13, Pv14, Pv27, Pv28, Pv2, Pv31, Pv56, Pv62, Pv68, Pv73, Pv78, Pv79, and Pv93
#> ℹ Variants retained: 1559 | Samples retained: 3 | Missing data: 13.53%
# see how many variants remained
nrow(vcf_outgrp@variants)
#> [1] 1559
# bind vcf_outgrp and vcf_ingrp (union - variable SNVs in any object)
vcf1 <- vcf_bind(vcf_ingrp, vcf_outgrp, mode = "union", absent_as = "hom_ref")
#> ℹ Binding 2 VCFArrow objects (union): 10000 variants, 18 total samples.
#> ℹ Absent genotypes will be filled as: hom_ref
# see how many variants remained
nrow(vcf1@variants)
#> [1] 10000With mode = "union", loci removed from an object stay
removed: a locus that one object removed by filtering (for example with
vcf_filter_maf()) but that another object still contains is
included in the result, and the genotypes of the object that removed it
are coded according to absent_as (missing,
./., by default). Binding in steps,
vcf_bind(vcf_bind(A, B, mode = "union"), C, mode = "union"),
and binding in one call, vcf_bind(A, B, C, mode = "union"),
therefore give the same result. To join datasets that were filtered
separately before the join, set recover_loci = TRUE: the
real genotypes of removed loci are then restored wherever an object’s
genotype files still hold them. With recover_loci = TRUE,
binding in steps can differ from binding in one call, because an
intermediate object keeps only the loci it contains, so bind all objects
in a single call.
Filtering with outgroup
Outgroups, which tend to have many fewer individuals than ingroups,
also have more missing data than ingroups due to phylogenetic effects.
Filtering the entire dataset often results in the removal of the
outgroup taxa when vcf_filter_missing() is used during
filtering to remove individuals with % missing data above some
threshold. It also results in fewer SNVs being retained after filtering.
The solution is to extract the outgroup taxa with
vcf_extract_samples() or vcf_extract_groups(),
filter the ingroup VCFArrow object, and add the outgroup taxa with
vcf_bind() using outgroup = TRUE.
With outgroup = TRUE, the result keeps exactly the loci
of the filtered ingroup, which must be the first object: loci removed
from the ingroup stay removed, and properties of the outgroup, such as
its missing data, cannot remove ingroup loci. The outgroup genotypes are
added for these loci wherever they exist, including loci the outgroup
dropped as invariant, so it does not matter whether the outgroup was
extracted with f_invar = TRUE or FALSE. By
contrast, mode = "union" also keeps loci found only in the
outgroup (see above).
# extract outgroup from VCFArrow
groups1 <- "OG"
vcf_outgrp <- vcf_extract_groups(vcf, groups1)
#> ℹ Compacting GT: 18 -> 3 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 1559 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pv120, Pv126, Pv13, Pv14, Pv27, Pv28, Pv2, Pv31, Pv56, Pv62, Pv68, Pv73, Pv78, Pv79, and Pv93
#> ℹ Variants retained: 1559 | Samples retained: 3 | Missing data: 13.53%
# filter VCFArrow ingroup, then bind outgroups
vcf1 <- vcf_extract_groups(vcf, groups1, keep = FALSE) |>
vcf_filter_indels() |>
vcf_filter_biallelic() |>
vcf_filter_coverage(10) |>
vcf_filter_missingness(.2) |>
vcf_filter_missing(.3) |>
vcf_filter_invariant() |>
vcf_filter_oneSNV() |>
vcf_bind(vcf_outgrp, outgroup = TRUE, absent_as = "missing")
#> ℹ Compacting GT: 18 -> 15 samples across 1 chunk
#> ℹ Applying invariant filter
#> ℹ Retained 8421 / 10000 variants (polymorphic at the allele level)
#> ℹ Removed samples: Pb2Jp, Pb2Scx, and Pb1Rd
#> ℹ Variants retained: 8421 | Samples retained: 15 | Missing data: 40.00%
#> ℹ Applying indel filter
#> ℹ Retained 7816 / 8421 variants (non-Indels)
#> ℹ Applying biallelic filter
#> ℹ Retained 7816 / 7816 variants (biallelic variants)
#> ℹ Applying read coverage filter
#> ℹ Set 26207 / 70192 called genotypes with DP < 10 to missing
#> ℹ Applying locus missingness filter
#> ℹ Retained 1396 / 7816 variants (per-variant missingness <= 0.2) | Missing data: 8.17%
#> ℹ Applying sample missingness filter
#> ℹ Variants retained: 1396 | Samples retained: 15 | Missing data: 8.17%
#> ℹ Applying invariant filter
#> ℹ Retained 1371 / 1396 variants (polymorphic at the allele level)
#> ℹ Applying unlinked SNV filter
#> ℹ Retained 1371 / 1371 variants (unlinked SNVs)
#> ℹ Binding 2 VCFArrow objects (outgroup): 1371 variants, 18 total samples.
#> ℹ Absent genotypes will be filled as: missing
# see how many variants remained
nrow(vcf1@variants)
#> [1] 1371
# filter - filter parameters in file name
fltr <- "_ingroup_filter"
# output a table and histogram of missing data
assess_vcf_missing_data(vcf1, res_path, species, paste0(project, postfix, fltr))
# apply the same filter to the full dataset (ingroup + outgroup)
vcf1 <- vcf |>
vcf_filter_indels() |>
vcf_filter_biallelic() |>
vcf_filter_coverage(10) |>
vcf_filter_missingness(.2) |>
vcf_filter_missing(.3) |>
vcf_filter_invariant() |>
vcf_filter_oneSNV()
#> ℹ Applying indel filter
#> ℹ Retained 9313 / 10000 variants (non-Indels)
#> ℹ Applying biallelic filter
#> ℹ Retained 9313 / 9313 variants (biallelic variants)
#> ℹ Applying read coverage filter
#> ℹ Set 32834 / 88565 called genotypes with DP < 10 to missing
#> ℹ Applying locus missingness filter
#> ℹ Retained 1071 / 9313 variants (per-variant missingness <= 0.2) | Missing data: 7.61%
#> ℹ Applying sample missingness filter
#> ℹ Variants retained: 1071 | Samples retained: 18 | Missing data: 7.61%
#> ℹ Applying invariant filter
#> ℹ Retained 1052 / 1071 variants (polymorphic at the allele level)
#> ℹ Applying unlinked SNV filter
#> ℹ Retained 1052 / 1052 variants (unlinked SNVs)
# see how many variants remained
nrow(vcf1@variants)
#> [1] 1052
# filter - filter parameters in file name
fltr <- "_all_filter"
# output a table and histogram of missing data
assess_vcf_missing_data(vcf1, res_path, species, paste0(project, postfix, fltr))Saving and copying VCFArrow objects
Filters that remove SNVs do not change the genotype files on disk,
which is a design decision: they only change which SNVs the object
includes, so they are fast and the filtered objects share the genotype
files. Functions that remove samples
(vcf_extract_samples(), vcf_extract_groups(),
vcf_filter_missing()) or change genotypes
(vcf_filter_adr(), vcf_filter_coverage())
write new genotype files holding only the retained samples and SNVs. The
function vcf_copy() creates a new object with its own copy
of the genotype files, unchanged. After filtering the VCFArrow object
you will also want to save it as a VCF. This is accomplished using the
function write_vcf(), which writes the retained samples and
SNVs, updates the INFO fields AC, AN, AF and NS where present, and
compresses the VCF with gzip when the file name ends in ‘.gz’ (or when
the ‘gzip’ flag is TRUE). With large VCFArrow objects compression has a
large overhead, so it is more efficient to save an uncompressed VCF and
then compress it later, for example with bgzip, which also
allows indexing it with tabix.
# write the VCFArrow object as a VCF (compressed with gzip, as the file name ends in .gz)
write_vcf(vcf1, out_file = file.path(res_path, paste0(project, postfix, "_filtered.vcf.gz")))
#> ℹ VCF is being written in 1 chunk
#> ✔ VCFArrow object successfully written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_filtered.vcf.gzConverting a VCF file to other population genetic and phylogenetic formats
All the following functions will take a VCFArrow object, and convert
it to other population genetic and phylogenetic formats,
exporting/writing a file of this format. Group/population information is
extracted from the VCFArrow object for those formats that require it.
The function vcf2genlight() automatically returns a
genlight object and optionally can also save it as an .rds file given by
out_file. Generally the vcf2genlight()
function is called within a script using functions of the
adegenet and poppr packages rather than
importing the genlight object. vcf2genlight() requires the
adegenet package.
res_path <- tempdir()
project <- "vaillantii_"
postfix <- "discosnp_sub"
fltr <- ""
##########
# dataset of unlinked SNVs to be transformed
vcf <- vcf_oneSNV
##########
# export data formats
# migrate-n https://peterbeerli.com/migrate-html5/
vcf2migrate(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_migrate.txt')))
#> ℹ Accumulating Migrate-N (S): 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing Migrate-N (S) file: 9 loci...
#> ✔ Migrate-N file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_migrate.txt
# arlequin http://cmpg.unibe.ch/software/arlequin35/
vcf2arlequin(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.arp')))
#> ℹ Accumulating Arlequin: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing Arlequin file...
#> ✔ Arlequin file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.arp
# structure https://web.stanford.edu/group/pritchardlab/structure.html
vcf2structure(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.str')))
#> ℹ Accumulating Structure: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing Structure file...
#> ✔ Structure file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.str
# faststructure http://rajanil.github.io/fastStructure/
# fastStructure adds .str to its --input name, so the file must end in .str
# (here read with --input=vaillantii_discosnp_sub_fs --format=str)
vcf2fstructure(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_fs.str')))
#> ℹ Accumulating Structure: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing Structure file...
#> ✔ Structure file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_fs.str
# sNMF http://membres-timc.imag.fr/Olivier.Francois/snmf/index.htm
vcf2snmf(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.geno')))
#> ℹ Formatting sNMF: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing sNMF file...
#> ✔ sNMF file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.geno
# Admixture https://dalexander.github.io/admixture/index.html
# takes as input binary PLINK (.bed), ordinary PLINK (.ped), or EIGENSTRAT (.geno) formatted files
# so a thin wrapper around vcf2plink_bed() plus optional generation of known-ancestry reference populations
vcf2admixture(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_admixture')))
#> ℹ Building PLINK: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing PLINK files...
#> ℹ Chromosome names were recoded as integers; mapping written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_admixture.chrommap
#> ✔ PLINK binary fileset written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_admixture.bed, /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_admixture.bim, /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_admixture.fam
# PLINK .bed https://www.cog-genomics.org/plink/1.9/formats#bed
vcf2plink_bed(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_plink')))
#> ℹ Building PLINK: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing PLINK files...
#> ℹ Chromosome names were recoded as integers; mapping written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_plink.chrommap
#> ✔ PLINK binary fileset written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_plink.bed, /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_plink.bim, /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_plink.fam
# PLINK .ped https://www.cog-genomics.org/plink/1.9/formats#ped
vcf2plink_ped(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_plink')))
#> ℹ Accumulating PLINK .ped: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing PLINK file...
#> ℹ Chromosome names were recoded as integers; mapping written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_plink.chrommap
#> ✔ PLINK text fileset written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_plink.ped, /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_plink.map
# eigenstrat https://github.com/DReichLab/EIG/tree/master
vcf2eigenstrat(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_eigenstrat')))
#> ℹ Building EIGENSTRAT: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing EIGENSTRAT files...
#> ℹ Chromosome names were recoded as integers; mapping written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_eigenstrat.chrommap
#> Warning: Chromosome codes go up to 899: EIGENSOFT reads chromosomes above its numchrom
#> parameter (default 22) as X, Y, ...
#> ℹ Set `numchrom: 899` (or higher) in the parameter file.
#> ✔ EIGENSTRAT fileset written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_eigenstrat.geno, /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_eigenstrat.ind, /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_eigenstrat.snp
# genepop https://gitlab.mbb.univ-montp2.fr/francois/genepop
vcf2genepop(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.gen')))
#> ℹ Accumulating Genepop: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing Genepop file...
#> ✔ Genepop file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.gen
# smartsnp https://github.com/ChristianHuber/smartsnp
# also writes the samples and their groups to <name>_samples.smartsnp,
# for smartsnp's sample_group argument
vcf2smartsnp(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.smartsnp')))
#> ℹ Building SmartSNP: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing SmartSNP file...
#> ✔ SmartSNP files written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.smartsnp and /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_samples.smartsnp
# bayescan https://github.com/mfoll/BayeScan
vcf2bayescan(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.bayescan')))
#> ℹ Accumulating BayesScan: 899 variants x 4 pops (0 MiB raw storage, vs 0 MiB with integer matrices)
#> ℹ Writing BayesScan file...
#> ✔ BayesScan file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.bayescan
# bayesass https://github.com/brannala/BA3
vcf2bayesass(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.bayesass')))
#> ℹ Accumulating BayesAss: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing BayesAss file...
#> ✔ BayesAss file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.bayesass
# treemix https://bitbucket.org/nygcresearch/treemix/wiki/Home
vcf2treemix(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.treemix')))
#> ℹ Building Treemix: 899 variants x 4 pops (0 MiB raw storage)
#> ℹ Writing Treemix file...
#> ✔ Treemix file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.treemix
# apparent https://github.com/halelab/apparent/tree/master
vcf2apparent(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.apparent')))
#> ℹ Accumulating Apparent: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing Apparent file...
#> ✔ Apparent file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.apparent
# related https://github.com/timothyfrasier/related
vcf2related(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.related')))
#> ℹ Accumulating Related: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing Related file...
#> ✔ Related file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.related
# long tidy dataframe of genotypes
vcf2gt_long(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.csv')), format = 'csv')
#> ℹ Writing gt_long: 899 variants x 18 samples
#> ✔ gt_long table written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.csv
# snapp https://www.beast2.org/snapp/
vcf2snapp(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_snapp.nex')))
#> ℹ Accumulating SNAPP: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing SNAPP file...
#> ✔ SNAPP file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_snapp.nex
# nexus - only SNVs, meant for SVDq analyses https://www.asc.ohio-state.edu/kubatko.2/software/SVDquartets/
vcf2nexus(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_sdvq.nex')))
#> ℹ Accumulating Nexus: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing Nexus file...
#> ✔ Nexus file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_sdvq.nex
# fasta https://www.ncbi.nlm.nih.gov/genbank/fastaformat/
vcf2fasta(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.fna')))
#> ℹ Accumulating FASTA: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing FASTA file...
#> ✔ FASTA file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.fna
# genlight object https://www.rdocumentation.org/packages/adegenet/versions/2.0.0/topics/genlight-class
# (requires the suggested package adegenet)
if (requireNamespace("adegenet", quietly = TRUE)) {
genlight <- vcf2genlight(vcf)
# genlight object with an optional save
genlight <- vcf2genlight(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '_genlight.rds')), save = TRUE)
}
#> ℹ Accumulating Genlight: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Building Genlight object...
#> ℹ Accumulating Genlight: 899 variants x 18 samples (0 MiB raw storage)
#> ℹ Building Genlight object...
#> ℹ Writing Genlight object...
#> ✔ Genlight object written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub_genlight.rds
##########
# datasets for analyses with linked SNVs
# (no linked SNVs in the tutorial dataset, see Filtering)
vcf <- vcf_multiSNV
##########
# export data formats
# fineRadStructure https://github.com/millanek/fineRADstructure
vcf2fineradstructure(vcf, out_file = file.path(res_path, paste0(project, postfix, fltr, '.finerad')))
#> ℹ Accumulating fineRADstructure: 0 variants x 18 samples (0 MiB raw storage)
#> ℹ Writing fineRADstructure file: 0 loci from 0 SNVs...
#> ✔ fineRADstructure file written to /tmp/RtmpCPU1t0/vaillantii_discosnp_sub.finerad