| Title: | Tidy Population Genetics |
| Version: | 1.1.0 |
| Description: | We provide a tidy grammar of population genetics, facilitating the manipulation and analysis of data on biallelic single nucleotide polymorphisms (SNPs). 'tidypopgen' scales to very large genetic datasets by storing genotypes on disk, and performing operations on them in chunks, without ever loading all data in memory. The full functionalities of the package are described in Carter et al. (2025) <doi:10.1111/2041-210x.70204>. |
| License: | GPL (≥ 3) |
| Encoding: | UTF-8 |
| Language: | en-GB |
| URL: | https://github.com/EvolEcolGroup/tidypopgen, https://evolecolgroup.github.io/tidypopgen/ |
| BugReports: | https://github.com/EvolEcolGroup/tidypopgen/issues |
| Depends: | R (≥ 3.5.0), dplyr (≥ 1.2.0), tibble |
| Imports: | bigparallelr, bigsnpr, bigstatsr, data.table, foreach, generics, lifecycle (≥ 1.0.2), ggplot2 (≥ 3.5.0), methods, MASS, patchwork, runner, rlang, RSpectra, sf, stats, tidyselect, tidyr, utils, Rcpp, vctrs, gtable |
| Suggests: | adegenet, admixtools, ape, broom, hexbin, hierfstat, knitr, detectRUNS, LEA, pcadapt, RhpcBLASctl, rmarkdown, rnaturalearth, rnaturalearthdata, readr, reticulate, testthat (≥ 3.1.7), vcfR, withr, xgboost, spelling |
| Additional_repositories: | https://evolecolgroup.r-universe.dev/ |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| LinkingTo: | Rcpp, RcppEigen, bigstatsr, rmio |
| LazyData: | true |
| Config/Needs/website: | rmarkdown |
| Config/roxygen2/version: | 8.1.0 |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-27 20:35:53 UTC; andrea |
| Author: | Evie Carter [aut],
Eirlys Tysall [aut],
Andrea Manica |
| Maintainer: | Andrea Manica <am315@cam.ac.uk> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-27 21:10:02 UTC |
tidypopgen: Tidy Population Genetics
Description
We provide a tidy grammar of population genetics, facilitating the manipulation and analysis of data on biallelic single nucleotide polymorphisms (SNPs). 'tidypopgen' scales to very large genetic datasets by storing genotypes on disk, and performing operations on them in chunks, without ever loading all data in memory. The full functionalities of the package are described in Carter et al. (2025) doi:10.1111/2041-210x.70204.
Author(s)
Maintainer: Andrea Manica am315@cam.ac.uk (ORCID) [copyright holder]
Authors:
Andrea Manica am315@cam.ac.uk (ORCID) [copyright holder]
Evie Carter
Eirlys Tysall
Other contributors:
Max Carter-Brown [contributor]
Jason Hodgson [contributor]
Christopher Chang (Author of PLINK 1.90: Hardy-Weinberg exact test code used in loci_hwe() and qc_report_loci(); runs of homozygosity algorithm followed by windows_indiv_roh(); LD pruning algorithm followed by loci_ld_prune()) [contributor, copyright holder]
Shaun Purcell (Author of PLINK 1.90: Hardy-Weinberg exact test code used in loci_hwe() and qc_report_loci(); runs of homozygosity algorithm followed by windows_indiv_roh(); LD pruning algorithm followed by loci_ld_prune()) [contributor, copyright holder]
Henrik Bengtsson (Author of countLines() in R.utils, modified for .vcf in count_vcf_variants()) [contributor, copyright holder]
Jan Wigginton (Author of the original Hardy-Weinberg exact test code (SNPHWE), on which the PLINK 1.90 code used in loci_hwe() is based) [contributor, copyright holder]
Florian Privé (Author of bigsnpr and bigstatsr, code from which is adapted in read_packedancestry_to_fbm(), gt_as_plink(), predict.gt_pca(), autoplot.gt_dapc() and loci_ld_clump()) [contributor, copyright holder]
Jérôme Goudet (Author of hierfstat, code from which is adapted in pop_global_stats(), pop_het_obs(), pop_het_exp() and indiv_inbreeding()) [contributor, copyright holder]
Robert Maier (Author of admixtools, code from which is adapted in gt_extract_f2()) [contributor, copyright holder]
Ryan Gutenkunst (Author of dadi, whose Spectrum class is translated to R in the tests of the site frequency spectra) [contributor, copyright holder]
Isaac Overcast (Author of easySFS, translated to R in the tests of the site frequency spectra) [contributor, copyright holder]
See Also
Useful links:
Report bugs at https://github.com/EvolEcolGroup/tidypopgen/issues
A $ method for gen_tibble objects
Description
A $ method for gen_tibble objects
Usage
## S3 replacement method for class 'gen_tbl'
x$i <- value
Arguments
x |
a gen_tibble |
i |
column name |
value |
a value to assign |
Value
a gen_tibble
Examples
example_gt <- load_example_gt("gen_tbl")
# Add a new column
example_gt$region <- "East"
example_gt
Pipe operator
Description
See 'magrittr::pipe \
Usage
lhs %>% rhs
Arguments
lhs |
A value or the magrittr placeholder. |
rhs |
A function call using the magrittr semantics. |
Value
The result of calling rhs(lhs).
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% count_loci()
Subsetting method for matrix_int_names
Description
Subsetting method for matrix_int_names
Assignment method for matrix_int_names
Usage
## S3 method for class 'matrix_int_names'
x[i, j, i_names = NULL, j_names = NULL, drop = TRUE]
## S3 replacement method for class 'matrix_int_names'
x[i, j, i_names = NULL, j_names = NULL] <- value
Arguments
x |
A matrix_int_names object |
i |
Row indices (numeric), row names (character), or missing) |
j |
Column indices (numeric), column names (character), or missing) |
i_names |
Optional integer row names to subset by |
j_names |
Optional integer column names to subset by |
drop |
Logical indicating whether to drop dimensions |
value |
A value to assign to the subsetted matrix |
Value
A subsetted matrix_int_names object
See Also
Other matrix_int_names_functions:
as.data.frame.matrix_int_names(),
col_names(),
matrix_int_names(),
print.matrix_int_names(),
row_names()
Examples
my_mat <- matrix_int_names(matrix(1:6, nrow = 2),
row_names = c(10L, 20L),
col_names = c(100L, 200L, 300L)
)
# subset by position
my_mat[1, 2:3, drop = FALSE]
# subset by integer names
my_mat[i_names = 20L, j_names = c(100L, 300L), drop = FALSE]
# assign by integer names
my_mat[i_names = 10L, j_names = 200L] <- 0L
my_mat
Attach a dendrogram panel to a heatmap
Description
Designed for use with |>. Accepts a ggplot or <heatmap_dendro> and returns a <heatmap_dendro> with the dendrogram panel inserted directly adjacent to the heatmap panel — pixel-perfect alignment regardless of axis label width. Can be chained to add dendrograms on both sides.
Usage
annotate_dendrogram(
plot,
hc,
side = c("left", "top"),
rel_size = 0.15,
line_color = "grey30",
line_size = 0.5
)
Arguments
plot |
A ggplot (from heatmap_pairwise()) or <heatmap_dendro> from a prior annotate_dendrogram() call. |
hc |
hclust object (from order functions that return hclust). |
side |
"left" (row dendrogram) or "top" (column dendrogram). |
rel_size |
Size of the dendrogram relative to the panel (null unit). |
line_color |
Segment colour. |
line_size |
Segment linewidth. |
Value
A <heatmap_dendro> object.
An arrange method for gen_tibble objects
Description
An arrange method for gen_tibble objects
Usage
## S3 method for class 'gen_tbl'
arrange(..., deparse.level = 1)
Arguments
... |
a gen_tibble and a data.frame or tibble |
deparse.level |
an integer controlling the construction of column names. |
Value
a gen_tibble
Examples
test_gt <- load_example_gt("gen_tbl")
test_gt %>% arrange(id)
An arrange method for grouped gen_tibble objects
Description
An arrange method for grouped gen_tibble objects
Usage
## S3 method for class 'grouped_gen_tbl'
arrange(..., deparse.level = 1)
Arguments
... |
a gen_tibble and a data.frame or tibble |
deparse.level |
an integer controlling the construction of column names. |
Value
a grouped gen_tibble
Examples
test_gt <- load_example_gt("grouped_gen_tbl")
test_gt %>% arrange(id)
test_gt <- load_example_gt("grouped_gen_tbl_sf")
test_gt %>% arrange(id)
Coercion method to data.frame for matrix_int_names
Description
This method converts a matrix_int_names object to a data.frame, preserving the integer row names. Otherwise, it works similarly to the default as.data.frame.matrix method.
Usage
## S3 method for class 'matrix_int_names'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)
Arguments
x |
A matrix_int_names object |
row.names |
Either a character or integer (as both are valid for
data.frame). If NULL, row names are inherited from the |
optional |
Ignored, included for compatibility with generic signature |
... |
Additional arguments passed to as.data.frame.matrix |
Value
A data.frame with integer row names if present, otherwise character row names
See Also
Other matrix_int_names_functions:
[.matrix_int_names(),
col_names(),
matrix_int_names(),
print.matrix_int_names(),
row_names()
Examples
# Create a matrix with integer row and column names
my_mat <- matrix_int_names(matrix(1:6, nrow = 2),
row_names = c(10L, 20L),
col_names = c(100L, 200L, 300L)
)
# Convert to data.frame
my_df <- as.data.frame(my_mat)
my_df
Convert runs of homozygosity to the format of detectRUNS
Description
Converts the runs found by windows_indiv_roh() to the data frame used by
the detectRUNS package, so that its functions to plot and summarise
runs (e.g. detectRUNS::plot_Runs(), detectRUNS::summaryRuns()) can be
used.
Usage
as_detectRUNS(x)
Arguments
x |
a tibble of runs, as returned by |
Value
a data frame with columns group (the grouping variables, pasted
with "." if there are several, or the id if the runs were found on an
ungrouped gen_tibble), id, chrom, nSNP, from, to and
lengthBps, in the order of x
Examples
bed_file <- system.file("extdata", "roh", "roh_sim.bed",
package = "tidypopgen"
)
sim_gt <- gen_tibble(bed_file, backingfile = tempfile(), quiet = TRUE)
sim_roh <- windows_indiv_roh(sim_gt %>% group_by(population))
head(as_detectRUNS(sim_roh))
Augment data with information from a gt_dapc object
Description
Augment for gt_dapc accepts a model object and a dataset and adds scores to
each observation in the dataset. Scores for each component are stored in a
separate column, which is given name with the pattern ".fittedLD1",
".fittedLD2", etc. For consistency with broom::augment.prcomp, a column
".rownames" is also returned; it is a copy of 'id', but it ensures that any
scripts written for data augmented with broom::augment.prcomp will work out
of the box (this is especially helpful when adapting plotting scripts).
Usage
## S3 method for class 'gt_dapc'
augment(x, data = NULL, k = NULL, ...)
Arguments
x |
A |
data |
the |
k |
the number of components to add |
... |
Not used. Needed to match generic signature only. |
Value
A gen_tibble containing the original data along with additional columns containing each observation's projection into PCA space.
See Also
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA and run DAPC (with missing genotypes, the loadings of the
# loci need the genotypes, `data`)
pca <- gt_pca(lobsters)
populations <- as.factor(lobsters$population)
dapc_res <- gt_dapc(pca,
n_pca = 6, n_da = 2, pop = populations, data = lobsters
)
# Augment the gen_tibble with the DAPC scores
augment(dapc_res, data = lobsters, k = 2)
Augment data with information from a gt_pca object
Description
Augment for gt_pca accepts a model object and a dataset and adds scores to
each observation in the dataset. Scores for each component are stored in a
separate column, which is given name with the pattern ".fittedPC1",
".fittedPC2", etc. For consistency with broom::augment.prcomp, a column
".rownames" is also returned; it is a copy of 'id', but it ensures that any
scripts written for data augmented with broom::augment.prcomp will work out
of the box (this is especially helpful when adapting plotting scripts).
Usage
## S3 method for class 'gt_pca'
augment(x, data = NULL, k = NULL, ...)
Arguments
x |
A |
data |
the |
k |
the number of components to add |
... |
Not used. Needed to match generic signature only. |
Value
A gen_tibble containing the original data along with additional columns containing each observation's projection into PCA space.
See Also
gt_pca() gt_pca_autoSVD() gt_pca_tidiers
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object
pca <- gt_pca(lobsters)
# Augment the gen_tibble with PCA scores
augment(pca, data = lobsters)
# Adjust the number of components to add
augment(pca, data = lobsters, k = 2)
Augment the loci table with information from a analysis object
Description
augment_loci add columns to the loci table of a gen_tibble related to
information from a given analysis.
Usage
augment_loci(x, data, ...)
Arguments
x |
An object returned by one of the |
data |
the |
... |
Additional parameters passed to the individual methods. |
Value
A loci tibble with additional columns. If data is missing, a tibble
of the information, with a column .rownames giving the loci names.
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA
pca <- gt_pca(lobsters)
# Augment the gen_tibble with the PCA scores
augment_loci(pca, data = lobsters)
Augment the loci table with information from a gt_pca object
Description
Augment for gt_pca accepts a model object and a gen_tibble and adds
loadings for each locus to the loci table. Loadings for each component are
stored in a separate column, which is given name with the pattern
".loadingPC1", ".loadingPC2", etc. If data is missing, then a tibble with
the loadings is returned.
Usage
## S3 method for class 'gt_pca'
augment_loci(x, data = NULL, k = NULL, ...)
Arguments
x |
A |
data |
the |
k |
the number of components to add |
... |
Not used. Needed to match generic signature only. |
Value
A gen_tibble with a loadings added to the loci tibble (accessible
with show_loci(). If data is missing, a tibble of loadings.
See Also
gt_pca() gt_pca_autoSVD() gt_pca_tidiers
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA
pca <- gt_pca(lobsters)
# Augment the gen_tibble with the PCA scores
augment_loci(pca, data = lobsters)
Augment data with information from a q_matrix object
Description
Augment for q_matrix accepts a model object and a dataset and adds Q values
to each observation in the dataset. Q values are stored in separate columns,
which is given name with the pattern ".Q1",".Q2", etc. For consistency with
broom::augment.prcomp, a column ".rownames" is also returned; it is a copy
of 'id', but it ensures that any scripts written for data augmented with
broom::augment.prcomp will work out of the box (this is especially helpful
when adapting plotting scripts).
Usage
## S3 method for class 'q_matrix'
augment(x, data = NULL, ...)
Arguments
x |
A |
data |
the |
... |
Not used. Needed to match generic signature only. |
Value
A gen_tibble containing the original data along with additional columns containing each observation's Q values.
Examples
# run the example only if we have the package installed
if (requireNamespace("LEA", quietly = TRUE)) {
example_gt <- load_example_gt("gen_tbl")
# Create a gt_admix object
admix_obj <- example_gt %>% gt_snmf(k = 1:3, project = "force")
# Extract a Q matrix
q_mat_k3 <- get_q_matrix(admix_obj, k = 3, run = 1)
# Augment the gen_tibble with Q values
augment(q_mat_k3, data = example_gt)
}
Autoplots for gt_cluster_pca objects
Description
For gt_cluster_pca, autoplot produces a plot of a metric of choice
('BIC', 'AIC' or 'WSS') against the number of clusters (k). This plot is
can be used to infer the best value of k, which corresponds to the smallest
value of the metric (the minimum in an 'elbow' shaped curve). In some cases,
there is not 'elbow' and the metric keeps decreasing with increasing k; in
such cases, it is customary to choose the value of k at which the decrease
in the metric reaches as plateau. For a programmatic way of choosing
k, use gt_cluster_pca_best_k().
Usage
## S3 method for class 'gt_cluster_pca'
autoplot(object, metric = c("BIC", "AIC", "WSS"), ...)
Arguments
object |
an object of class |
metric |
the metric to plot on the y axis, one of 'BIC', 'AIC', or 'WSS' (with sum of squares) |
... |
not currently used. |
Details
autoplot produces simple plots to quickly inspect an object. They are not
customisable; we recommend that you use ggplot2 to produce publication
ready plots.
Value
a ggplot2 object
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object
pca <- gt_pca(lobsters)
# Run clustering on the first 10 PCs
cluster_pca <- gt_cluster_pca(
x = pca,
n_pca = 10,
k_clusters = c(1, 5),
method = "kmeans",
n_iter = 1e5,
n_start = 10,
quiet = FALSE
)
# Autoplot BIC
autoplot(cluster_pca, metric = "BIC")
# # Autoplot AIC
autoplot(cluster_pca, metric = "AIC")
# # Autoplot WSS
autoplot(cluster_pca, metric = "WSS")
Autoplots for gt_dapc objects
Description
For gt_dapc, the following types of plots are available:
-
screeplot: a plot of the eigenvalues of the discriminant axes -
scoresa scatterplot of the scores of each individual on two discriminant axes (defined byld) -
loadingsa plot of loadings of all loci for a discriminant axis (chosen withld) -
componentsa bar plot showing the probability of assignment to each cluster
Usage
## S3 method for class 'gt_dapc'
autoplot(
object,
type = c("screeplot", "scores", "loadings", "components"),
ld = NULL,
group = NULL,
n_col = 1,
...
)
Arguments
object |
an object of class |
type |
the type of plot (one of "screeplot", "scores", "loadings", and "components") |
ld |
the principal components to be plotted: for scores, a pair of
values e.g. c(1,2); for |
group |
a vector of group memberships to order the individuals in "components" plot. If NULL, the clusters used for the DAPC will be used. |
n_col |
for |
... |
not currently used. |
Details
autoplot produces simple plots to quickly inspect an object. They are not
customisable; we recommend that you use ggplot2 to produce publication
ready plots.
Value
a ggplot2 object
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA and run DAPC (with missing genotypes, the loadings of the
# loci need the genotypes, `data`)
pca <- gt_pca(lobsters)
populations <- as.factor(lobsters$population)
dapc_res <- gt_dapc(pca,
n_pca = 6, n_da = 2, pop = populations, data = lobsters
)
# Screeplot
autoplot(dapc_res, type = "screeplot")
# Scores plot
autoplot(dapc_res, type = "scores", ld = c(1, 2))
# Loadings plot
autoplot(dapc_res, type = "loadings", ld = 1)
# Components plot
autoplot(dapc_res, type = "components", group = populations)
Autoplots for indiv_roh objects
Description
Plots of runs of homozygosity found by
windows_indiv_roh(), equivalent to the plots of detectRUNS. Runs are
coloured (or split) by group if the gen_tibble was grouped. The
following types of plots are available:
-
runs: the runs of each individual along each chromosome (asdetectRUNS::plot_Runs()); -
stacked: the runs of each group stacked along each chromosome, one run per line, ordered by start (asdetectRUNS::plot_StackedRuns()); -
coverage: the percentage of individuals of each group in a run along each chromosome (asdetectRUNS::plot_SnpsInRuns()anddetectRUNS::plot_manhattanRuns(), computed from the runs rather than at each locus); -
froh: the inbreeding coefficient F_ROH, the total length of the runs of an individual over the length of the genome (withfroh_by = "individual", one point per individual, by group) or of each chromosome (withfroh_by = "chromosome", the mean of each group) (asdetectRUNS::plot_InbreedingChr()); the length of a chromosome is its largest position, as indetectRUNS; -
violin: the distribution of the total (or mean, seemethod) length of the runs of each individual, by group (asdetectRUNS::plot_ViolinRuns()); -
length_class: the percentage of runs in each class of length, by group (asdetectRUNS::plot_DistributionRuns()).
Usage
## S3 method for class 'indiv_roh'
autoplot(
object,
type = c("runs", "stacked", "coverage", "froh", "violin", "length_class"),
chromosome = NULL,
froh_by = c("individual", "chromosome"),
method = c("sum", "mean"),
classes = c(0, 2, 4, 8, 16),
...
)
Arguments
object |
an object of class |
type |
the type of plot ( |
chromosome |
the chromosomes to plot (by default, all those with runs;
for |
froh_by |
for |
method |
for |
classes |
for |
... |
not currently used. |
Details
Individuals with no runs count in coverage, froh and violin (with no
runs, or a length of 0).
autoplot produces simple plots to quickly inspect an object. They are not
customisable; we recommend that you use ggplot2 to produce publication
ready plots.
Value
a ggplot2 object
Examples
# a simulated dataset of three populations with increasing inbreeding
bed_file <- system.file("extdata", "roh", "roh_sim.bed",
package = "tidypopgen"
)
sim_gt <- gen_tibble(bed_file, backingfile = tempfile(), quiet = TRUE)
sim_roh <- windows_indiv_roh(sim_gt %>% group_by(population))
autoplot(sim_roh, type = "runs", chromosome = "3")
autoplot(sim_roh, type = "coverage")
autoplot(sim_roh, type = "froh")
autoplot(sim_roh, type = "length_class")
Autoplots for qc_report_indiv objects
Description
For qc_report_indiv, the following types of plots are available:
-
scatter: a plot of missingness and observed heterozygosity within individuals. -
relatedness: a histogram of paired kinship coefficients -
histogram: for gen_tibbles containing pseudohaploid data, a histogram of missingness, split by ploidy.
Usage
## S3 method for class 'qc_report_indiv'
autoplot(
object,
type = c("scatter", "relatedness", "histogram"),
miss_threshold = 0.05,
kings_threshold = NULL,
...
)
Arguments
object |
an object of class |
type |
the type of plot ( |
miss_threshold |
a threshold for the accepted rate of missingness within individuals |
kings_threshold |
an optional numeric, a threshold of relatedness for the sample |
... |
not currently used. |
Details
autoplot produces simple plots to quickly inspect an object. They are not
customisable; we recommend that you use ggplot2 to produce publication
ready plots.
Value
a ggplot2 object. For relatedness plots of a report created
from a grouped gen_tibble, a named list of ggplot2 objects, one for
each group.
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
example_gt <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Create QC report for individuals
indiv_report <- example_gt %>% qc_report_indiv()
# Autoplot missingness and observed heterozygosity
autoplot(indiv_report, type = "scatter", miss_threshold = 0.1)
# Create QC report with kinship filtering
indiv_report_rel <-
example_gt %>% qc_report_indiv(kings_threshold = "second")
# Autoplot relatedness
autoplot(indiv_report_rel, type = "relatedness", kings_threshold = "second")
Autoplots for qc_report_loci objects
Description
For qc_report_loci, the following types of plots are available:
-
overview: an UpSet plot, giving counts of snps over the threshold for missingness, minor allele frequency, and Hardy-Weinberg equilibrium P-value, and visualising the interaction between these. -
all: a four panel plot, containingmissing high maf,missing low maf,hwe, andsignificant hweplots -
missing: a histogram of proportion of missing data -
missing low maf: a histogram of the proportion of missing data for snps with low minor allele frequency -
missing high maf:a histogram of the proportion of missing data for snps with high minor allele frequency -
maf: a histogram of minor allele frequency -
hwe: a histogram of HWE exact test p-values -
significant hwe: a histogram of significant HWE exact test p-values
Usage
## S3 method for class 'qc_report_loci'
autoplot(
object,
type = c("overview", "all", "missing", "missing low maf", "missing high maf", "maf",
"hwe", "significant hwe"),
maf_threshold = 0.05,
miss_threshold = 0.01,
hwe_p = 0.01,
...
)
Arguments
object |
an object of class |
type |
the type of plot (one of |
maf_threshold |
default 0.05, a threshold for the accepted rate of minor allele frequency of loci |
miss_threshold |
default 0.01, a threshold for the accepted rate of missingness per loci |
hwe_p |
default 0.01, a threshold of significance for Hardy-Weinberg exact p-values |
... |
not currently used. |
Details
autoplot produces simple plots to quickly inspect an object. They are not
customisable; we recommend that you use ggplot2 to produce publication
ready plots.
Value
a ggplot2 object
Examples
# Create a gen_tibble
bed_file <-
system.file("extdata", "related", "families.bed", package = "tidypopgen")
example_gt <- gen_tibble(bed_file,
backingfile = tempfile("families"),
quiet = TRUE,
valid_alleles = c("1", "2")
)
loci_report <- example_gt %>% qc_report_loci()
# Plot the QC report overview
autoplot(loci_report, type = "overview")
# Plot the QC report all
autoplot(loci_report, type = "all")
# Plot missing data
autoplot(loci_report, type = "missing")
# Plot missing with low maf
autoplot(loci_report, type = "missing low maf", maf_threshold = 0.05)
# Plot missing with high maf
autoplot(loci_report, type = "missing high maf", maf_threshold = 0.05)
# Plot maf
autoplot(loci_report, type = "maf", maf_threshold = 0.05)
# Plot hwe
autoplot(loci_report, type = "hwe", hwe_p = 0.01)
# Plot significant hwe
autoplot(loci_report, type = "significant hwe", hwe_p = 0.01)
Autoplots for gt_admix objects
Description
For gt_admix, the following types of plots are available:
-
cv: the cross-validation error for each value ofk -
barplota standard barplot of the admixture proportions
Usage
## S3 method for class 'gt_admix'
autoplot(object, type = c("cv", "barplot"), k = NULL, run = NULL, ...)
Arguments
object |
an object of class |
type |
the type of plot (one of "cv", and "barplot") |
k |
the value of |
run |
the run to plot (for |
... |
additional arguments to be passed to autoplot method for
q_matrices |
Details
autoplot produces simple plots to quickly inspect an object. They are not
customisable; we recommend that you use ggplot2 to produce publication
ready plots.
This autoplot will automatically rearrange individuals according to their id
and any grouping variables if an associated 'data' gen_tibble is provided. To
avoid any automatic re-sorting of individuals, set arrange_by_group and
arrange_by_indiv to FALSE. See autoplot.q_matrix for further details.
Value
a ggplot2 object
Examples
# Read example gt_admix object
admix_obj <-
readRDS(system.file("extdata", "anolis", "anole_adm_k3.rds",
package = "tidypopgen"
))
# Cross-validation plot
autoplot(admix_obj, type = "cv")
# Basic barplot
autoplot(admix_obj, k = 3, run = 1, type = "barplot")
# Barplot with individuals arranged by Q proportion
# (using additional arguments, see `autoplot.q_matrix` for details)
autoplot(admix_obj,
k = 3, run = 1, type = "barplot", annotate_group = TRUE,
arrange_by_group = TRUE, arrange_by_indiv = TRUE,
reorder_within_groups = TRUE
)
Autoplots for gt_pca objects
Description
For gt_pca, the following types of plots are available:
-
screeplot: a plot of the eigenvalues of the principal components (currently it plots the singular value) -
scoresa scatterplot of the scores of each individual on two principal components (defined byk) -
loadingsa plot of loadings of all loci for a given component (chosen withk)
Usage
## S3 method for class 'gt_pca'
autoplot(object, type = c("screeplot", "scores", "loadings"), k = NULL, ...)
Arguments
object |
an object of class |
type |
the type of plot (one of "screeplot", "scores" and "loadings") |
k |
the principal components to be plotted: for scores, a pair of values
e.g. c(1,2); for |
... |
not currently used. |
Details
autoplot produces simple plots to quickly inspect an object. They are not
customisable; we recommend that you use ggplot2 to produce publication
ready plots.
Value
a ggplot2 object
Examples
library(ggplot2)
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object
pca <- gt_pca(lobsters)
# Screeplot
autoplot(pca, type = "screeplot")
# Scores plot
autoplot(pca, type = "scores")
# Colour by population
autoplot(pca, type = "scores") + aes(colour = lobsters$population)
# Scores plot of different components
autoplot(pca, type = "scores", k = c(1, 3)) +
aes(colour = lobsters$population)
Autoplots for gt_pcadapt objects
Description
For gt_pcadapt, the following types of plots are available:
-
qq: a quantile-quantile plot of the p-values frompcadapt(wrappingbigsnpr::snp_qq()) -
manhattana manhattan plot of the p-values frompcadapt(wrappingbigsnpr::snp_manhattan())
Usage
## S3 method for class 'gt_pcadapt'
autoplot(object, type = c("qq", "manhattan"), ...)
Arguments
object |
an object of class |
type |
the type of plot (one of "qq", and "manhattan") |
... |
further arguments to be passed to |
Details
autoplot produces simple plots to quickly inspect an object. They are
not customisable; we recommend that you use ggplot2 to produce publication
ready plots.
Value
a ggplot2 object
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object (the lobsters have some missing genotypes, which do not
# need to be imputed)
pca <- gt_pca(lobsters)
# Create a gt_pcadapt object
pcadapt_obj <- gt_pcadapt(lobsters, pca, k = 2)
# Plot the p-values from pcadapt
autoplot(pcadapt_obj, type = "qq")
# Plot the manhattan plot of the p-values from pcadapt
autoplot(pcadapt_obj, type = "manhattan")
Autoplot for pairwise distance matrices
Description
This function provides a convenient way to visualize pairwise distance matrices (e.g., Fst, IBS) as heatmaps using ggplot2. It supports both matrix and tidy tibble formats, and can optionally reorder rows/columns using either an explicit ordering vector or a function (e.g. hierarchical clustering).
Usage
## S3 method for class 'pairwise_matrix'
autoplot(object, order = NULL, ...)
## S3 method for class 'pairwise_tbl'
autoplot(object, order = NULL, ...)
Arguments
object |
A square numeric matrix OR a data.frame/tibble with 3 columns: names1, names2, value (half-matrix representation). |
order |
Optional ordering specification. Can be:
|
... |
Additional arguments (not currently used). Included for compatibility with autoplot generic. |
Value
A ggplot object.
Examples
example_gt <- load_example_gt("gen_tbl")
# With a pairwise matrix:
fst_dist <- example_gt %>%
group_by(population) %>%
pairwise_pop_fst(method = "Nei87", type = "pairwise")
autoplot(fst_dist)
# Explicit ordering
autoplot(
fst_dist,
order = rev(rownames(fst_dist))
)
# Hierarchical clustering
autoplot(
fst_dist,
order = function(x) {
stats::hclust(stats::as.dist(x), method = "complete")
}
)
# With a tidy tibble of distances:
fst_tidy <- example_gt %>%
group_by(population) %>%
pairwise_pop_fst(method = "Nei87", type = "tidy")
autoplot(fst_tidy)
autoplot(
fst_tidy,
order = function(x) {
stats::hclust(stats::as.dist(x))
}
)
Autoplots for q_matrix objects
Description
This autoplot will automatically rearrange individuals according to their id
and any grouping variables if an associated 'data' gen_tibble is provided. To
avoid any automatic re-sorting of individuals, set arrange_by_group and
arrange_by_indiv to FALSE.
Usage
## S3 method for class 'q_matrix'
autoplot(
object,
data = NULL,
annotate_group = TRUE,
arrange_by_group = TRUE,
arrange_by_indiv = TRUE,
reorder_within_groups = FALSE,
...
)
Arguments
object |
A Q matrix object (as returned by |
data |
An associated tibble (e.g. a |
annotate_group |
Boolean determining whether to annotate the plot with the group information |
arrange_by_group |
Boolean determining whether to arrange the
individuals by group. Groups are ordered as by the grouped functions
(see |
arrange_by_indiv |
Boolean determining whether to arrange the
individuals by their individual id within each group (groups are arranged
first if |
reorder_within_groups |
Boolean determining whether to reorder the
individuals within each group based on their ancestry proportion (note that
this is not advised if you are making multiple plots, as you would get a
different order for each plot!). Groups keep the order set by
|
... |
not currently used. |
Value
a barplot of individuals, coloured by ancestry proportion
Examples
# Read example gt_admix obejct
admix_obj <-
readRDS(system.file("extdata", "anolis", "anole_adm_k3.rds",
package = "tidypopgen"
))
# Extract a Q matrix
q_mat_k3 <- get_q_matrix(admix_obj, k = 3, run = 1)
# Basic autoplot
autoplot(q_mat_k3, annotate_group = FALSE, arrange_by_group = FALSE)
# To arrange individuals by group and by Q proportion
autoplot(q_mat_k3,
annotate_group = TRUE, arrange_by_group = TRUE,
arrange_by_indiv = TRUE, reorder_within_groups = TRUE
)
Plot site frequency spectra
Description
Plot the site frequency spectra computed by pop_sfs() (bar plots of the
number of sites by allele count, one panel per population),
pairwise_pop_sfs() (heatmaps of the joint spectra, one panel per pair of
populations), or a single spectrum returned with type = "array" (a bar
plot for one population, a heatmap for two). The output of
pop_sfs_preview() is plotted as the number of segregating sites for each
projection, one panel per population, with the projection chosen by
default marked. Spectra of more than two populations (from
nwise_pop_sfs()) cannot be plotted; use pairwise_pop_sfs() to plot the
joint spectra of pairs of populations.
Usage
## S3 method for class 'sfs'
autoplot(object, masked = FALSE, log = NULL, min_sites = NULL, ...)
## S3 method for class 'pop_sfs_tbl'
autoplot(object, masked = FALSE, log = NULL, ...)
## S3 method for class 'pairwise_sfs_tbl'
autoplot(object, masked = FALSE, log = NULL, min_sites = NULL, ...)
## S3 method for class 'sfs_preview_tbl'
autoplot(object, ...)
Arguments
object |
the output of |
masked |
boolean, whether to show the masked cells of the spectra.
Defaults to |
log |
boolean, whether to show the numbers of sites on a log scale
(the y axis of bar plots, the colour scale of heatmaps). If |
min_sites |
the lower limit of the log colour scale of heatmaps:
cells with fewer (but more than 0) sites are shown with the lightest
colour. If |
... |
currently unused. |
Details
The masked cells of the spectra (the corners, i.e. sites monomorphic in
the projected sample, and the cells that were folded out in a folded
spectrum; see pop_sfs()) are not shown by default. In heatmaps, the
numbers of sites are shown on a log scale by default, and empty cells
are left blank. As the projection spreads each locus over many cells, many
cells have a tiny fraction of a site: on a log scale, the colour scale
starts at min_sites (by default, a thousandth of the largest number of
sites in a cell), and cells with fewer sites are shown with its lightest
colour (as vmin in the plots of dadi).
Value
a ggplot2 object.
See Also
pop_sfs(), pairwise_pop_sfs(), pop_sfs_preview()
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# the 1D spectrum of each population
example_gt %>%
pop_sfs(n_proj = 4) %>%
autoplot()
# the joint spectrum of each pair of populations
example_gt %>%
pairwise_pop_sfs(n_proj = 4, folded = FALSE) %>%
autoplot()
# a single spectrum
sfs_2d <- example_gt %>%
pairwise_pop_sfs(n_proj = 4, folded = FALSE, type = "array")
autoplot(sfs_2d$pop1.pop2)
# the number of segregating sites for each projection
example_gt %>%
pop_sfs_preview() %>%
autoplot()
Draw the blocks of bootstrap replicates
Description
This function is designed for developers of packages that add bootstrap
methods to the generics of tidypopgen (e.g. for genotype likelihoods), so
that their replicates resample the same blocks as the methods of
tidypopgen. The loci are divided into non-overlapping blocks
that never span chromosomes, defined as in jackknife_stats_generic() (a
number of SNPs, of base pairs, or a size in centiMorgans), and each
replicate draws as many blocks as there are, with replacement.
Usage
bootstrap_blocks(
loci_table,
n_bootstrap,
block_size,
size_unit = c("snp", "cM", "bp")
)
Arguments
loci_table |
a dataframe including at least a column 'chromosome', and
additionally a column 'position' if |
n_bootstrap |
the number of replicates. |
block_size |
the size of the blocks, in the unit of |
size_unit |
either "snp", "cM" or "bp". If "snp", the block size is in number of loci. If "cM", the block size is in centiMorgans. If "bp", the block size is in base pairs. |
Details
The blocks are drawn with the random number generator of R: set its seed
(e.g. with set.seed()) for reproducible replicates. The matrix of weights
has one value per replicate and block; to bound its memory, its size is
capped at 1e9 values (option tidypopgen.sfs_max_bootstrap_weights).
Value
a list with block_id (the block of each locus, an integer from
1 to the number of blocks, numbered in their order of appearance) and
weights (an integer matrix with the number of times each block, in
columns, is drawn in each replicate, in rows).
Examples
example_gt <- load_example_gt("gen_tbl")
set.seed(1)
blocks <- bootstrap_blocks(show_loci(example_gt),
n_bootstrap = 3,
block_size = 2, size_unit = "snp"
)
blocks$block_id
blocks$weights
Block bootstrap of site frequency spectra
Description
Compute bootstrap replicates of the site frequency spectra of
pop_sfs(), pairwise_pop_sfs() and nwise_pop_sfs(), by resampling
blocks of loci with replacement. Replicates are used to estimate the
uncertainty of statistics computed from the spectra, or of the parameters
of demographic models fitted with dadi, moments or fastsimcoal2
(see write_sfs() to write the replicates in their formats).
Usage
bootstrap_pop_sfs(.x, ...)
## S3 method for class 'gen_tbl'
bootstrap_pop_sfs(
.x,
n_bootstrap = 100,
block_size,
size_unit = c("snp", "cM", "bp"),
n_proj = NULL,
folded = TRUE,
ancestral = NULL,
type = c("tidy", "array"),
n_cores = bigstatsr::nb_cores(),
...
)
bootstrap_pairwise_pop_sfs(.x, ...)
## S3 method for class 'gen_tbl'
bootstrap_pairwise_pop_sfs(
.x,
n_bootstrap = 100,
block_size,
size_unit = c("snp", "cM", "bp"),
n_proj = NULL,
folded = TRUE,
ancestral = NULL,
type = c("tidy", "array"),
fastest = c("last", "first"),
n_cores = bigstatsr::nb_cores(),
...
)
bootstrap_nwise_pop_sfs(.x, ...)
## S3 method for class 'gen_tbl'
bootstrap_nwise_pop_sfs(
.x,
n_bootstrap = 100,
block_size,
size_unit = c("snp", "cM", "bp"),
n_proj = NULL,
folded = TRUE,
ancestral = NULL,
type = c("tidy", "array"),
fastest = c("last", "first"),
max_cells = 1e+07,
n_cores = bigstatsr::nb_cores(),
...
)
Arguments
.x |
a |
... |
other arguments passed to specific methods, currently unused. |
n_bootstrap |
the number of bootstrap replicates. |
block_size |
the size of the blocks of loci that are resampled. |
size_unit |
the unit of |
n_proj |
the number of allele copies to project each population to:
either a single value used for all populations, a vector with one value
per population (in the order of the groups), or a vector named with the
group labels. If |
folded |
boolean, whether to fold the spectrum (the default, as the
ancestral allele is not usually known). If |
ancestral |
the ancestral allele of each locus, used to polarise
unfolded spectra: either the name of a column of the loci table (see
|
type |
the type of object to return, either "tidy" (the default) or "array". |
n_cores |
number of cores to be used, it defaults to
|
fastest |
the order of the cells of each spectrum in the tidy
output: "last" (the default) keeps the order of the populations, so
that the rows are sorted by the number of allele copies in the first
population, then in the second (the number of copies in the second
population changes fastest, as in the files written by |
max_cells |
the maximum number of cells of all the replicates (the
number of cells of the joint spectrum times |
Details
The loci are divided into non-overlapping blocks that never span more
than one chromosome, defined as in the jackknife_* functions (e.g.
jackknife_pop_tajimas_d()): blocks of block_size SNPs, base pairs or
centiMorgans (the latter requires the genetic_dist column of the loci
table). Blocks should be larger than the extent of linkage
disequilibrium, so that they are approximately independent. Each
replicate draws, with replacement, as many blocks as there are (as the
bootstrap of dadi, Misc.bootstraps_from_dd_chunks()). With
block_size = 1 and size_unit = "snp", single SNPs are resampled (as the
--resample-vcf option of easySFS), which ignores linkage.
A spectrum is a sum over loci, so the spectrum of a replicate is the sum
of the spectra of the blocks it drew (counting each block as many times as
it was drawn). The genotypes are therefore read only once, to compute the
spectrum of each block. Missing data are dealt with by projection, as in
pop_sfs(), with the same projections (n_proj) for all replicates: if
n_proj is NULL, they are chosen from all the loci with
pop_sfs_preview(). The blocks are drawn with the random number
generator of R, so use set.seed() to make the replicates reproducible.
Value
If type = "tidy", a tibble with the columns of the tidy output
of pop_sfs(), pairwise_pop_sfs() or nwise_pop_sfs(), and a column
replicate (after the group columns) with the number of the replicate.
If type = "array", a list with one element per replicate, each of
which is what pop_sfs(), pairwise_pop_sfs() or nwise_pop_sfs()
return with type = "array" (lists of sfs objects, or an sfs object).
In both cases, the attribute bootstrap_blocks is a matrix with the
number of times each block (columns, numbered in the order in which they
appear in the loci table) was drawn in each replicate (rows), and the
tibble also has the attributes n_proj and folded.
See Also
pop_sfs(), write_sfs(), jackknife_stats_generic()
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
set.seed(1)
# resample blocks of 2 SNPs
boot <- example_gt %>%
bootstrap_pop_sfs(n_bootstrap = 10, block_size = 2, n_proj = 2)
boot
# the 95% interval of the number of sites in each cell
boot %>%
dplyr::group_by(group, allele_count) %>%
dplyr::summarise(
lower = stats::quantile(n_sites, 0.025),
upper = stats::quantile(n_sites, 0.975)
)
# the joint spectra of each pair, as arrays
boot_2d <- example_gt %>%
bootstrap_pairwise_pop_sfs(
n_bootstrap = 5, block_size = 2, n_proj = 2,
type = "array"
)
boot_2d[[1]]$pop1.pop2
Combine method for gt_admix objects
Description
Combine method for gt_admix objects
Usage
## S3 method for class 'gt_admix'
c(..., match_attributes = TRUE)
Arguments
... |
A list of |
match_attributes |
boolean, determining whether all attributes (id,
group and algorithm) of the |
Value
A gt_admix object with the combined data
Examples
# run the example only if we have the package installed
if (requireNamespace("LEA", quietly = TRUE)) {
example_gt <- load_example_gt("gen_tbl")
# Create a gt_admix object
admix_obj <- example_gt %>% gt_snmf(k = 1:3, project = "force")
# Create a second gt_admix object
admix_obj2 <- example_gt %>% gt_snmf(k = 2:4, project = "force")
# Combine the two gt_admix objects
new_admix_obj <- c(admix_obj, admix_obj2)
summary(new_admix_obj)
}
Combine a gen_tibble to a data.frame or tibble by column
Description
A cbind() method to merge gen_tibble objects with data.frames and normal
tibbles. Whilst this works, it is not ideal as it does not check the order of
the tables, and we suggest that you use dplyr::left_join() instead. Note
that cbind will not combine two gen_tibbles (i.e. it will NOT combine
markers for the same individuals)
Usage
## S3 method for class 'gen_tbl'
cbind(..., deparse.level = 1)
## S3 method for class 'grouped_gen_tbl'
cbind(..., deparse.level = 1)
Arguments
... |
a gen_tibble and a data.frame or tibble |
deparse.level |
an integer controlling the construction of column names.
See |
Details
As in dplyr::bind_cols() (which dplyr uses to cbind() grouped
tibbles), duplicated column names are made unique (e.g. population...2
and population...4), with a message. If a grouping variable is renamed,
the result is no longer grouped. The columns id and
genotypes of the gen_tibble can not be duplicated, as renaming them
would break it.
Value
a gen_tibble
Examples
example_gt <- load_example_gt("gen_tbl")
# Create a dataframe to combine with the gen_tibble
df <- data.frame(region = c("A", "A", "B", "B", "A", "B", "B"))
# Combine the gen_tibble with the dataframe
example_gt <- cbind(example_gt, df)
Get or set column names for matrix_int_names
Description
This function reliably returns integer names if present, otherwise character dimnames. Use this instead of colnames() if you need guaranteed dispatch.
Usage
col_names(x)
## Default S3 method:
col_names(x)
## S3 method for class 'matrix_int_names'
col_names(x)
col_names(x) <- value
## Default S3 replacement method:
col_names(x) <- value
## S3 replacement method for class 'matrix_int_names'
col_names(x) <- value
Arguments
x |
A matrix_int_names object |
value |
a vector of integer or character column names to set, replacing the current one. |
Value
Integer or character vector of column names, or NULL
See Also
Other matrix_int_names_functions:
[.matrix_int_names(),
as.data.frame.matrix_int_names(),
matrix_int_names(),
print.matrix_int_names(),
row_names()
Examples
my_mat <- matrix_int_names(matrix(1:6, nrow = 2),
row_names = c(10L, 20L),
col_names = c(100L, 200L, 300L)
)
col_names(my_mat)
# set character names instead
col_names(my_mat) <- c("a", "b", "c")
col_names(my_mat)
Count the number of loci in a gen_tibble
Description
Count the number of loci in gen_tibble (or directly from its genotype
column).
Usage
count_loci(.x, ...)
## S3 method for class 'tbl_df'
count_loci(.x, ...)
## S3 method for class 'vctrs_bigSNP'
count_loci(.x, ...)
Arguments
.x |
a |
... |
currently unused. |
Value
the number of loci
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% count_loci()
Distruct colours
Description
Colours in the palette used by distruct
Usage
distruct_colours
Format
A vector of 56 hex colours
Details
The 56 distinct colours of the palette of distruct (which repeats 4 of its
60 colours), in their original order. scale_fill_distruct() recycles them
when there are more groups.
Source
The colour palette of distruct (https://rosenberglab.stanford.edu/distruct.html).
References
Rosenberg N.A. (2004) DISTRUCT: a program for the graphical display of population structure. Molecular Ecology Notes 4: 137-138.
Tidyverse methods for gt objects
Description
A filter method for gen_tibble objects
Usage
## S3 method for class 'gen_tbl'
filter(..., deparse.level = 1)
Arguments
... |
a gen_tibble and a data.frame or tibble |
deparse.level |
an integer controlling the construction of column names. |
Value
a gen_tibble
Examples
test_gt <- load_example_gt("gen_tbl")
test_gt %>% filter(id %in% c("a", "c"))
A filter method for grouped gen_tibble objects
Description
A filter method for grouped gen_tibble objects
Usage
## S3 method for class 'grouped_gen_tbl'
filter(..., deparse.level = 1)
Arguments
... |
a gen_tibble and a data.frame or tibble |
deparse.level |
an integer controlling the construction of column names. |
Value
a grouped gen_tibble
Examples
test_gt <- load_example_gt("grouped_gen_tbl")
test_gt %>% filter(id %in% c("a", "c"))
test_gt <- load_example_gt("grouped_gen_tbl_sf")
test_gt %>% filter(id %in% c("a", "c"))
Filter individuals based on a relationship threshold
Description
This function takes a matrix of x by y individuals containing relatedness coefficients and returns the maximum set of individuals that contains no relationships above the given threshold.
Usage
filter_high_relatedness(
matrix,
.x = NULL,
kings_threshold = NULL,
verbose = FALSE
)
Arguments
matrix |
a square symmetric matrix of individuals containing relationship coefficients |
.x |
a |
kings_threshold |
a threshold over which |
verbose |
boolean whether to report to screen |
Details
Individuals are removed greedily, as in
caret::findCorrelation(): individuals are considered in order of
decreasing mean relatedness, and for each pair related above
kings_threshold, the first individual is removed if its mean
relatedness is larger than the mean of the remaining matrix without the
second individual, and the second one otherwise. No pair above the
threshold is left, but the set of individuals kept is not guaranteed to
be the largest possible.
Missing relationship coefficients (e.g. KING kinship for pairs of individuals with no loci genotyped in both) are not evidence of relatedness: such pairs are treated as not related, with a warning.
Value
a list where '1' is individual ID's to retain, '2' is individual ID's to remove, and '3' is a boolean where individuals to keep are TRUE and individuals to remove are FALSE
Examples
example_gt <- load_example_gt("gen_tbl")
# Calculate relationship matrix
king_matrix <- example_gt %>% pairwise_king(as_matrix = TRUE)
# Filter individuals with threshold above 0.2
filter_high_relatedness(king_matrix, example_gt, kings_threshold = 0.2)
Find duplicates in the loci table
Description
This function finds duplicated SNPs by checking the positions within each chromosome. It can return a list of duplicated SNPs or a logical value indicating whether there are any duplicated loci.
Usage
find_duplicated_loci(.x, error_on_false = FALSE, list_duplicates = TRUE, ...)
Arguments
.x |
a vector of class |
error_on_false |
logical, if |
list_duplicates |
logical, if |
... |
other arguments passed to specific methods. |
Value
If list_duplicates is TRUE, returns a character vector of
duplicated loci names (character(0) when none). If list_duplicates is
FALSE, returns TRUE when no duplicates exist and FALSE when duplicates are
present. If error_on_false is TRUE and duplicates exist, an error is
thrown.
Examples
example_gt <- load_example_gt("gen_tbl")
show_loci(example_gt) <- test_loci <- data.frame(
big_index = c(1:6),
name = paste0("rs", 1:6),
chromosome = paste0("chr", c(1, 1, 1, 1, 1, 1)),
position = as.integer(c(3, 3, 5, 65, 343, 46)),
genetic_dist = as.double(rep(0, 6)),
allele_ref = c("A", "T", "C", "G", "C", "T"),
allele_alt = c("T", "C", NA, "C", "G", "A")
)
show_loci(example_gt)
# Find which loci are duplicated
example_gt %>% find_duplicated_loci()
Constructor for a gen_tibble
Description
A gen_tibble stores genotypes for individuals in a tidy format. DESCRIBE
here the format
Usage
gen_tibble(
x,
...,
valid_alleles = c("A", "T", "C", "G"),
missing_alleles = c("0", "."),
backingfile = NULL,
allow_duplicates = FALSE,
quiet = FALSE
)
## S3 method for class 'character'
gen_tibble(
x,
...,
parser = c("cpp", "vcfR"),
n_cores = 1,
chunk_size = NULL,
valid_alleles = c("A", "T", "C", "G"),
missing_alleles = c("0", "."),
backingfile = NULL,
allow_duplicates = FALSE,
names_as_int = FALSE,
chromosomes_as_int = FALSE,
phased = FALSE,
quiet = FALSE
)
## S3 method for class 'matrix'
gen_tibble(
x,
indiv_meta,
loci,
...,
ploidy = 2,
valid_alleles = c("A", "T", "C", "G"),
missing_alleles = c("0", "."),
backingfile = NULL,
allow_duplicates = FALSE,
phased = FALSE,
quiet = FALSE
)
Arguments
x |
can be:
|
... |
if |
valid_alleles |
a vector of valid allele values; it defaults to 'A','T', 'C' and 'G'. |
missing_alleles |
a vector of values in the BIM file/loci dataframe that indicate a missing value for the allele value (e.g. when we have a monomorphic locus with only one allele). It defaults to '0' and '.' (the same as PLINK 1.9). |
backingfile |
the path, including the file name without extension, for
backing files used to store the data (they will be given a .bk and .RDS
automatically). If |
allow_duplicates |
logical. If TRUE, the tibble will allow duplicated loci (those with genomic coordinate (chromosome + position) or locus name appearing more than once). If FALSE, an error will be thrown if duplicated loci are found. These validations run before backing files are saved. Default is FALSE. |
quiet |
provide information on the files used to store the data |
parser |
the name of the parser used for VCF, either "cpp" to use a
fast C++ parser (the default), or "vcfR" to use the R package |
n_cores |
the number of cores used to read a VCF file with
|
chunk_size |
the number of loci or individuals (depending on the format)
processed at a time (currently used if |
names_as_int |
logical. If TRUE, locus names will be
converted to integers. Only used when |
chromosomes_as_int |
logical. If TRUE, chromosomes will be stored as
integer codes rather than as a factor. Only used when |
phased |
logical. If TRUE, the genotypes are stored with their phase,
giving a phased |
indiv_meta |
a list, data.frame or tibble with compulsory columns 'id'
and 'population', plus any additional metadata of interest. This is only
used if |
loci |
a data.frame or tibble, with compulsory columns 'name',
'chromosome', and 'position','genetic_dist', 'allele_ref' and 'allele_alt'.
This is only used if |
ploidy |
the ploidy of the samples (either a single value, or a vector of values for mixed ploidy). Only used if creating a gen_tibble from a matrix of data; otherwise, ploidy is determined automatically from the data as they are read. |
Details
-
VCF files: the fast
cppparser is used by default. BothcppandvcfRparsers attempt to establish ploidy from the first variant; if that variant is found in a sex chromosome (or mtDNA), the parser will fail with 'Error: a genotype has more than max_ploidy alleles...'. To successful import such a VCF, change the order of variants so that the first chromosome is an autosome using a tool such asvcftools. Individuals with a missing genotype ('.') on the first variant get their ploidy from their first genotype that is not '.': thecppparser looks for it in the next 1,000 variants only (so that the search does not slow down parsing), thevcfRparser in the whole file. Individuals with no such genotype get the largest ploidy of the other individuals (or 2, if no ploidy is known). Currently, only biallelic SNPs are supported. If haploid variants (e.g. sex chromosomes) are included in the VCF, they are not transformed into homozygous calls. Instead, reference alleles will be coded as 0 and alternative alleles will be coded as 1. The phase of phased genotypes (e.g.0|1) is ignored, unlessphased = TRUE(see below). -
PLINK files (.bed, .ped, or a bigSNP .rds): the individual information (from the .fam file, or the first six columns of the .ped file) is stored in the same columns for all formats: the individual ID as
id; the family ID aspopulation(unless it is the same as the individual ID for all individuals); the paternal and maternal IDs aspaternal_IDandmaternal_ID; sex assex, a factor with levels "female" (PLINK code 2) and "male" (code 1); and the phenotype asphenotype, a factor with levels "control" (code 1) and "case" (code 2), or a number for a quantitative phenotype (with values other than 1, 2, 0 and -9). Missing values (0 for parents and sex, 0 or -9 for a case/control phenotype, and -9 for a quantitative one) are NA, andpaternal_ID,maternal_ID,sexandphenotypeare only created if they have some non-missing values.gt_as_plink()writes these columns back to PLINK files. -
packedancestry files: the genotype file can be in either of the two layouts of EIGENSOFT, GENO (one record per locus) or TGENO (one record per individual, "transposed", as in recent releases of the Allen Ancient DNA Resource, AADR); the layout is detected from the header of the file, whatever its extension (.geno or .tgeno). A TGENO file is read into memory in one go if it is smaller than 2 GB (and otherwise in slabs of loci, using up to 2 GB of memory). When loading packedancestry files, missing alleles will be converted from 'X' to NA
Phased genotypes: with
phased = TRUE,gen_tibble()creates a phasedgen_tibbleof diploid individuals, which also knows which allele of each genotype is on the first and which on the second haplotype (e.g.0|1versus1|0), as needed by haplotype based statistics. Phased genotypes are stored in the same file backed matrix as unphased ones (see phased_encoding), so that all other functions work on phasedgen_tibbles as usual, treating their genotypes as ordinary dosages of the alternate allele.is_phased()tests whether agen_tibbleis phased, andshow_haplotypes()returns its haplotypes. Phased genotypes can be read from VCF files (with parser "cpp"), in which all individuals have to be diploid and all genotypes phased (with|, e.g.0|1): any unphased genotype (with/, including0/0and./.) is an error, naming the individual and the locus, and a genotype with a missing allele (e.g..|.,0|., or a single.) is missing. They can also be created from a matrix of haplotypes, with two rows per individual (the first and second haplotypes of individualiare rows2 * i - 1and2 * i) and one column per locus, containing 0 (reference allele), 1 (alternate allele) orNA(if either haplotype is missing, the genotype is missing).gt_merge_vcfs()andgt_concat_vcfs()also read phased VCF files withphased = TRUE. Functions that write genotypes keep the phase where they can:gt_as_vcf()writes phased genotypes (0|1), subsetting,gt_save(),gt_load(),gt_order_loci()andgt_update_backingfile()keep phased data phased, and rbind() keeps the phase when bothgen_tibbles are phased (it then never swaps or flips alleles), and discards it (with a message) when only one of them is phased. Imputation (gt_impute_simple(),gt_impute_xgboost()) is not available for phasedgen_tibbles.
Value
an object of the class gen_tbl.
Note
Helper functions for accessing gen_tibble object attributes and
checking gen_tibble ploidy can be found in gt_helper_functions.R
Examples
# Create a gen_tibble from a .bed file
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Create a gen_tibble from a .vcf file
vcf_path <-
system.file("extdata", "anolis",
"punctatus_t70_s10_n46_filtered.recode.vcf.gz",
package = "tidypopgen"
)
gen_tibble(vcf_path, quiet = TRUE, backingfile = tempfile("anolis_"))
# Create a phased gen_tibble from a phased .vcf file
phased_vcf <-
system.file("extdata", "phased_example.vcf", package = "tidypopgen")
phased_gt <- gen_tibble(phased_vcf,
phased = TRUE,
quiet = TRUE, backingfile = tempfile("phased_")
)
show_haplotypes(phased_gt)
# Create a gen_tibble from a matrix of genotypes:
test_indiv_meta <- data.frame(
id = c("a", "b", "c"),
population = c("pop1", "pop1", "pop2")
)
test_genotypes <- rbind(
c(1, 1, 0, 1, 1, 0),
c(2, 1, 0, 0, 0, 0),
c(2, 2, 0, 0, 1, 1)
)
test_loci <- data.frame(
name = paste0("rs", 1:6),
chromosome = paste0("chr", c(1, 1, 1, 1, 2, 2)),
position = as.integer(c(3, 5, 65, 343, 23, 456)),
genetic_dist = as.double(rep(0, 6)),
allele_ref = c("A", "T", "C", "G", "C", "T"),
allele_alt = c("T", "C", NA, "C", "G", "A")
)
gen_tibble(
x = test_genotypes,
loci = test_loci,
indiv_meta = test_indiv_meta,
valid_alleles = c("A", "T", "C", "G"),
quiet = TRUE
)
Restore the class of a tibble from its genotypes column
Description
Some dplyr operations return tibbles that have lost the class of a
gen_tibble, such as the data frames returned by pick() or across()
within summarise(), reframe() or mutate(), the result of reframe(),
or as_tibble(). Their genotypes column, however, keeps its class.
The generics of tidypopgen therefore have fallback methods for data
frames (and grouped data frames), which use restore_genotypes_tbl() to
give back the tibble its class, as given by genotypes_tbl_class() for
its genotypes column, and then dispatch again.
Usage
genotypes_tbl_class(genotypes, ...)
## Default S3 method:
genotypes_tbl_class(genotypes, ...)
## S3 method for class 'vctrs_bigSNP'
genotypes_tbl_class(genotypes, ...)
restore_genotypes_tbl(.x, generic = "this function")
Arguments
genotypes |
the |
... |
currently unused |
.x |
a data frame or tibble with a |
generic |
the name of the generic for which the class is restored, used in the error message if the restored class has no method |
Details
Packages that build their own tibbles on tidypopgen (e.g. for genotype
likelihoods) add a method to genotypes_tbl_class() for the
class of their genotypes column, so that their own methods of the
tidypopgen generics are used after the class is restored.
Value
genotypes_tbl_class() returns the class of the tibble that holds
the genotypes column ("gen_tbl" for a vctrs_bigSNP column), or
NULL for a column of an unknown class.
restore_genotypes_tbl() returns .x as a tibble with the class
given by genotypes_tbl_class(), and its grouped version (e.g.
"grouped_gen_tbl") if .x is grouped. A rowwise_df is ungrouped. It
stops with an error if .x already has that class, as the generic would
otherwise dispatch to the fallback method again.
Return a single P matrix from a gt_admix object
Description
This function retrieves a single P matrix from a gt_admix object
based on the specified k value and run number.
Usage
get_p_matrix(x, ..., k, run)
Arguments
x |
A |
... |
Not used |
k |
The k value of the desired P matrix |
run |
The run number of the desired P matrix |
Value
A single P matrix from the gt_admix object
Examples
# Read example gt_admix object
admix_obj <-
readRDS(system.file("extdata", "anolis", "anole_adm_k3.rds",
package = "tidypopgen"
))
# Extract a P matrix
get_p_matrix(admix_obj, k = 3, run = 1)
Return a single Q matrix from a gt_admix object
Description
This function retrieves a single Q matrix from a gt_admix object
based on the specified k value and run number.
Usage
get_q_matrix(x, ..., k, run)
Arguments
x |
A |
... |
Not used |
k |
The k value of the desired Q matrix |
run |
The run number of the desired Q matrix |
Value
A single Q matrix from the gt_admix object
Examples
# Read example gt_admix obejct
admix_obj <-
readRDS(system.file("extdata", "anolis", "anole_adm_k3.rds",
package = "tidypopgen"
))
# Extract a Q matrix
get_q_matrix(admix_obj, k = 3, run = 1)
Columns that identify groups in a tidy output, as tidypopgen names them
Description
This function is designed for developers of packages that add methods to
the generics of tidypopgen for grouped data (e.g. for genotype
likelihoods), so that their tidy outputs identify the groups as the
methods of tidypopgen do: a single group column when there is one
grouping variable, and one column per grouping variable when there are
several (as dplyr::summarise()), keeping their types (e.g. a factor keeps
its levels). For outputs on pairs of groups, each group of the pair has one
column per grouping variable, named with a suffix (e.g. population_1 and
population_2, with suffix = "_1" and "_2"), also when there is a
single grouping variable.
Usage
group_columns(keys, idx, suffix = NULL, other_names = character())
Arguments
keys |
a data frame with one row per group and one column per
grouping variable, as returned by |
idx |
the index of the group of each row of the output. |
suffix |
|
other_names |
the names of the other columns of the output: the group columns must not have any of these names (an error asks to rename the grouping variables). |
Value
a tibble with one row per element of idx.
See Also
group_labels() for the labels of the groups.
Examples
keys <- data.frame(population = c("a", "a", "b"), sex = c("F", "M", "F"))
group_columns(keys, c(1, 3))
group_columns(keys[1], c(1, 3))
group_columns(keys, c(1, 3), suffix = "_1")
Labels of groups, as tidypopgen names them
Description
This function is designed for developers of packages that add methods to
the generics of tidypopgen for grouped data (e.g. for genotype
likelihoods), so that their outputs label the groups as the methods of
tidypopgen do. A group is labelled by the value of its grouping variable
or, with several grouping variables, by their values pasted with "." (as
the names of the pairs of groups, e.g. fst_pop1.pop2).
Usage
group_labels(keys)
Arguments
keys |
a data frame with one row per group and one column per
grouping variable, as returned by |
Value
a character vector with the label of each group.
See Also
group_columns() for the columns that identify the groups in a
tidy output.
Examples
keys <- data.frame(population = c("a", "a"), sex = c("F", "M"))
group_labels(keys)
Add an simple feature geometry to a gen_tibble
Description
gt_add_sf adds an active sf geometry column to a gen_tibble object. The
resulting gen_tbl inherits from sf and can be used with functions from
the sf package. It is possible to either create a sf::sfc geometry
column from coordinates, or to provide an existing geometry column (which
will then become the active geometry for sf).
Usage
gt_add_sf(x, coords = NULL, crs = NULL, sfc_column = NULL)
Arguments
x |
a |
coords |
a vector of length 2, giving the names of the x and y columns
in |
crs |
the coordinate reference system of the coordinates. If this is not
set, it will be set to the default value of |
sfc_column |
the name of an |
Value
a gen_tibble object with an additional geometry column (and thus
belonging also to sf class).
Examples
example_gt <- load_example_gt("gen_tbl")
# Add some coordinates
example_gt <- example_gt %>% mutate(
longitude = c(0, 0, 2, 2, 0, 2, 2),
latitude = c(51, 51, 49, 49, 51, 41, 41)
)
# Convert lat and long to sf:
example_gt <- gt_add_sf(x = example_gt, coords = c("longitude", "latitude"))
# Check class
class(example_gt)
Reorder the q matrices based on the grouping variable
Description
This function reorders the q matrices in a gt_admix object based on the
grouping variable. This is useful before plotting when the samples from each
group are not adjacent to each other in the q matrix.
Usage
gt_admix_reorder_q(x, group = NULL)
Arguments
x |
a |
group |
a character vector with the grouping variable (if there is no
grouping variable info in |
Value
a gt_admix object with the q matrices reordered
Examples
# run the example only if we have the package installed
if (requireNamespace("LEA", quietly = TRUE)) {
example_gt <- load_example_gt("gen_tbl")
# Create a gt_admix object
admix_obj <- example_gt %>% gt_snmf(k = 1:3, project = "force")
# The $id in admix_obj is the same as in the gen_tibble
admix_obj$id
# Reorder the q matrices based on the grouping variable
admix_obj <- gt_admix_reorder_q(admix_obj,
group = example_gt$population
)
# The $id in admix_obj is now reordered according to the population
admix_obj$id
}
Run ADMIXTURE from R
Description
This function is a wrapper around ADMIXTURE. We recommend you have a look
at tidygenclust, which provides a much faster native R implementation of
the ADMIXTURE algorithm through gt_radmix(), and is compatible with
gen_tibble objects.
This function runs ADMIXTURE, taking either a gen_tibble or a file as an
input. This is a wrapper that runs ADMIXTURE from the command line, and reads
the output into R. It can run multiple values of k and multiple repeats for
each k.
Usage
gt_admixture(
x,
k,
n_runs = 1,
crossval = FALSE,
n_cores = 1,
seed = NULL,
conda_env = "auto",
outdir = NULL
)
Arguments
x |
a |
k |
an integer giving the number of clusters |
n_runs |
the number of runs for each k value (defaults to 1) |
crossval |
boolean, should cross validation be used to assess the fit (defaults to FALSE) |
n_cores |
number of cores (defaults to 1) |
seed |
the seed for the random number generator, either a vector of
length |
conda_env |
the name of the conda environment to use. "none" forces the use of a local copy, whilst any other string will direct the function to use a custom conda environment. |
outdir |
optional path to write intermediate admixture output files. If not specified, defaults to a temporary file. Use this argument to store intermediate files. |
Details
This is a wrapper for the command line program ADMIXTURE. It can either use a binary present in the main environment, or use a copy installed in a conda environment.
Value
an object of class gt_admix consisting of a list with the following
elements:
-
kthe number of clusters -
Qa matrix with the admixture proportions -
Pa matrix with the allele frequencies, with one row per locus in the same order as the loci of the input (as given byshow_loci()for agen_tibble, or the bim file for a bed file). ADMIXTURE reports the frequency of the second allele in the bim file, which for agen_tibbleisallele_ref. -
loga log of the output generated by ADMIXTURE (usually printed on the screen when running from the command line) -
cvthe cross validation error (ifcrossvalis TRUE) -
loglikthe log likelihood of the model -
idthe id column of the inputgen_tibble(if applicable) -
groupthe group column of the inputgen_tibble(if applicable)
References
Alexander, D.H., Novembre, J. and Lange, K. (2009) ‘Fast model-based estimation of ancestry in unrelated individuals’, Genome Research, 19(9), pp. 1655–1664. Available at: https://doi.org/10.1101/gr.094052.109.
Examples
# run the example only if we have the package installed
## Not run:
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
lobsters <- lobsters %>% group_by(population)
gt_admixture(lobsters,
k = 2:3, seed = c(1, 2),
n_runs = 2, crossval = TRUE
)
## End(Not run)
Convert a gen_tibble to a genind object from adegenet
Description
This function converts a gen_tibble to a genind object from adegenet.
genind objects support arbitrary ploidy (including mixed-ploidy data
across individuals), so this works on diploid, polyploid and mixed-ploidy
gen_tibble objects alike.
Usage
gt_as_genind(x)
Arguments
x |
a |
Value
a genind object
Note
pseudohaploid individuals are treated as diploid (ploidy 2) using their stored genotype counts (dosage 0/2) directly, the same convention used by other tools (e.g. PLINK) when handling pseudohaploid data.
Examples
example_gt <- load_example_gt("gen_tbl")
# Convert to genind
gt_genind <- example_gt %>% gt_as_genind()
# Check object class
class(gt_genind)
Convert a gen_tibble to a genlight object from adegenet
Description
This function converts a gen_tibble to a genlight object from adegenet
Usage
gt_as_genlight(x, chunk_size = NULL)
Arguments
x |
a |
chunk_size |
the number of loci processed at a time (rounded up to a multiple of 8). If left to NULL, chunks of about 10 million genotypes are used. |
Details
The chromosome and position of each locus are stored in the genlight
object, and the alleles are stored as "ref/alt" in loc.all (genlight
counts the second allele, i.e. the alternate allele). As genlight only
supports single letter alleles, loc.all is not set (with a warning) if any
locus has a missing or multi-character allele.
The genotypes are read in chunks of loci, so that the full matrix of
genotypes is never loaded in memory; the result is the same as building the
genlight from that matrix.
Value
a genlight object
Examples
example_gt <- load_example_gt("gen_tbl")
# Convert to genlight
gt_genlight <- example_gt %>% gt_as_genlight()
# Check object class
class(gt_genlight)
Convert a gentibble to a .geno file for sNMF from the LEA package
Description
This function writes a .geno file from a gen_tibble. Unless a file path
is given, a file with suffix .geno is written in the same location as the
.rds and .bk files that underpin the gen_tibble.
Usage
gt_as_geno_lea(x, file = NULL)
Arguments
x |
|
file |
the .geno filename with a path, or NULL (the default) to use the location of the backing files. |
Details
The genotypes are read and written directly from the file backed matrix (one locus at a time), so this function also works on datasets that do not fit in memory.
Value
the path of the .geno file
Note
the .geno format only supports haploid or diploid data, so this
function only works on diploid (or pseudohaploid) gen_tibble objects.
Pseudohaploid data is simply treated as regular diploid genotype counts
(dosage 0/2), the same convention used by other tools (e.g. PLINK).
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
# Write a geno file
gt_as_geno_lea(example_gt, file = paste0(tempfile(), "_example.geno"))
Convert a gen_tibble to a data.frame compatible with hierfstat
Description
This function converts a gen_tibble to a data.frame formatted
to be used by hierfstat functions.
Usage
gt_as_hierfstat(x)
Arguments
x |
a |
Value
a data.frame with a column 'pop' and further column representing the genotypes (with alleles recoded as 1 and 2)
Note
hierfstat only supports haploid or diploid data, so this function
only works on diploid (or pseudohaploid) gen_tibble objects.
Pseudohaploid data is simply treated as regular diploid genotype counts
(dosage 0/2), the same convention used by other tools (e.g. PLINK).
Examples
example_gt <- load_example_gt("gen_tbl")
# Convert to hierfstat format
gt_hierfstat <- example_gt %>% gt_as_hierfstat()
# Check object class
class(gt_hierfstat)
Export a gen_tibble object to PLINK bed format
Description
This function exports all the information of a gen_tibble object into a
PLINK bed, ped or raw file (and associated files, i.e. .bim and .fam for
.bed; .fam for .ped).
Usage
gt_as_plink(
x,
file = NULL,
type = c("bed", "ped", "raw"),
overwrite = TRUE,
chromosomes_as_int = FALSE
)
Arguments
x |
a |
file |
a character string giving the path to output file. If left to NULL, the output file will have the same path and prefix of the backingfile. |
type |
one of "bed", "ped" or "raw" |
overwrite |
boolean whether to overwrite the file. |
chromosomes_as_int |
boolean whether to use the integer representation of the chromosomes |
Details
If the gen_tibble has been read in from vcf format, family.ID in the
resulting plink files will be the same as sample.ID. If the gen_tibble has a
grouping variable, this will be used as the family.ID in the resulting plink
files (with several grouping variables, their values are pasted with ".",
e.g. pop1.F); otherwise, the population is used as the family.ID. Parents,
sex and phenotype are taken from the columns paternal_ID, maternal_ID,
sex and phenotype, if present, as created by gen_tibble() when
reading PLINK files (bed, ped or bigSNP rds): sex is written as 1 for
"male", 2 for "female" and 0 (unknown) otherwise; phenotype as 1 for
"control" and 2 for "case", and other values (e.g. a quantitative
phenotype) as they are; missing parents are written as 0, and missing
phenotypes as -9. Genotypes are read and written directly from the file
backed matrix, so all formats can be written for datasets that do not fit in
memory (but note that ped and raw files are much larger, and thus slower to
write, than bed files).
Value
the path of the saved file
Note
PLINK's bed, ped and raw formats only support diploid data, so this
function only works on diploid (or pseudohaploid) gen_tibble objects.
Pseudohaploid data is simply treated as regular diploid genotype counts
(dosage 0/2), the same convention used by PLINK itself.
Examples
example_gt <- load_example_gt("gen_tbl")
# Write a bed file
example_gt %>% gt_as_plink(type = "bed", file = paste0(tempfile(), "_plink"))
# Write a ped file
example_gt %>% gt_as_plink(type = "ped", file = paste0(tempfile(), "_plink"))
# Write a raw file
example_gt %>% gt_as_plink(type = "raw", file = paste0(tempfile(), "_plink"))
Convert a gen_tibble to a VCF
Description
This function write a VCF from a gen_tibble. Phased genotypes (see
phased in gen_tibble()) are written as phased (e.g. 0|1), and unphased
ones as unphased (e.g. 0/1). The genotypes are read and
written in chunks of loci, so that this works on datasets that do not fit in
memory.
Usage
gt_as_vcf(x, file = NULL, chunk_size = NULL, overwrite = FALSE)
Arguments
x |
a |
file |
the .vcf file name with a path, or NULL (the default) to use the location of the backing files. |
chunk_size |
the number of loci processed at a time (also used for the number of chromosomes processed at a time when writing the contig lines of the header). If left to NULL, 100,000 loci are processed at a time. |
overwrite |
logical, should the file be overwritten if it already exists? |
Value
the path of the .vcf file
Examples
example_gt <- load_example_gt("gen_tbl")
# Write a vcf file
example_gt %>% gt_as_vcf()
Run K-clustering on principal components
Description
This function implements the clustering procedure used in Discriminant
Analysis of Principal Components (DAPC, Jombart et al. 2010). This procedure
consists in running successive K-means with an increasing number of clusters
(k), after transforming data using a principal component analysis (PCA). For
each model, several statistical measures of goodness of fit are computed,
which allows to choose the optimal k using the function
gt_cluster_pca_best_k(). See details for a description of how to select the
optimal k and vignette("adegenet-dapc") for a tutorial.
Usage
gt_cluster_pca(
x = NULL,
n_pca = NULL,
k_clusters = c(1, round(nrow(x$u)/10)),
method = c("kmeans", "ward"),
n_iter = 1e+05,
n_start = 10,
quiet = FALSE
)
Arguments
x |
a |
n_pca |
number of principal components to be fed to the LDA. |
k_clusters |
number of clusters to explore, either a single value, or a vector of length 2 giving the minimum and maximum (e.g. 1:5). If left NULL, it will use 1 to the number of pca components divided by 10 (a reasonable guess). |
method |
either 'kmeans' or 'ward' |
n_iter |
number of iterations for kmeans (only used if
|
n_start |
number of starting points for kmeans (only used if
|
quiet |
boolean on whether to silence outputting information to the screen (defaults to FALSE) |
Value
a gt_cluster_pca object, which is a subclass of gt_pca with an
additional element 'cluster', a list with elements:
'method' the clustering method (either kmeans or ward)
'n_pca' number of principal components used for clustering
'k' the k values explored by the function
'WSS' within sum of squares for each k
'AIC' the AIC for each k
'BIC' the BIC for each k
'groups' a list, with each element giving the group assignments for a given k
References
Jombart T, Devillard S and Balloux F (2010) Discriminant analysis of principal components: a new method for the analysis of genetically structured populations. BMC Genetics 11:94. doi:10.1186/1471-2156-11-94
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object
pca <- gt_pca(lobsters)
# Run clustering on the first 10 PCs
gt_cluster_pca(
x = pca,
n_pca = 10,
k_clusters = c(1, 5),
method = "kmeans",
n_iter = 1e5,
n_start = 10,
quiet = FALSE
)
# Alternatively, use method "ward"
gt_cluster_pca(
x = pca,
n_pca = 10,
k_clusters = c(1, 5),
method = "ward",
quiet = FALSE
)
Find the best number of clusters based on principal components
Description
This function selects the best k value based on a chosen metric and
criterion. It is equivalent to plotting the metric against the k values,
and selecting the k that fulfills a given criterion (see details for an
explanation of each criterion). This function simply adds an element 'best_k'
to the gt_cluster_pca returned by gt_cluster_pca(). The choice can be
over-ridden simply by assigning a different value to that element (e.g. for
an object x and a desired k of 8, simply use x$best_k <- 8)
Usage
gt_cluster_pca_best_k(
x,
stat = c("BIC", "AIC", "WSS"),
criterion = c("diffNgroup", "min", "goesup", "smoothNgoesup", "goodfit"),
quiet = FALSE
)
Arguments
x |
a |
stat |
a statistics, one of "BIC", "AIC" or "WSS" |
criterion |
one of "diffNgroup", "min", "goesup", "smoothNgoesup", "goodfit", see details for a discussion of each approach. |
quiet |
boolean on whether to silence outputting information to the screen (defaults to FALSE) |
Details
The analysis of data simulated under various population genetics models (see reference) suggested an ad-hoc rule for the selection of the optimal number of clusters. First important result is that BIC seems more efficient than AIC and WSS to select the appropriate number of clusters (see example). The rule of thumb consists in increasing K until it no longer leads to an appreciable improvement of fit (i.e., to a decrease of BIC). In the most simple models (island models), BIC decreases until it reaches the optimal K, and then increases. In these cases, the best rule amounts to choosing the lowest K. In other models such as stepping stones, the decrease of BIC often continues after the optimal K, but is much less steep, so a change in slope can be taken as an indication of where the best k lies.
This function provides a programmatic way to select k. Note that it is highly recommended to look at the graph of BIC versus the numbers of clusters, to understand and validate the programmatic selection. The criteria available in this function are:
"diffNgroup": differences between successive values of the summary statistics (by default, BIC) are split into two groups using a Ward's clustering method (see ?hclust), to differentiate sharp decrease from mild decreases or increases. The retained K is the one before the first group switch. This criterion appears to work well for island/hierarchical models, and decently for isolation by distance models, albeit with some instability. It can be confounded by an initial, very sharp decrease of the test statistics. IF UNSURE ABOUT THE CRITERION TO USE, USE THIS ONE.
"min": the model with the minimum summary statistics (as specified by stat argument, BIC by default) is retained. Is likely to work for simple island model, using BIC. It is likely to fail in models relating to stepping stones, where the BIC always decreases (albeit by a small amount) as K increases. In general, this approach tends to over-estimate the number of clusters.
"goesup": the selected model is the K after which increasing the number of clusters leads to increasing the summary statistics. Suffers from inaccuracy, since i) a steep decrease might follow a small 'bump' of increase of the statistics, and ii) increase might never happen, or happen after negligible decreases. Is likely to work only for clear-cut island models.
"smoothNgoesup": a variant of "goesup", in which the summary statistics is first smoothed using a lowess approach. Is meant to be more accurate than "goesup" as it is less prone to stopping to small 'bumps' in the decrease of the statistics.
"goodfit": another criterion seeking a good fit with a minimum number of clusters. This approach does not rely on differences between successive statistics, but on absolute fit. It selects the model with the smallest K so that the overall fit is above a given threshold.
Value
a 'gt_cluster_pca' object with an added element 'best_k'
References
Jombart T, Devillard S and Balloux F (2010) Discriminant analysis of principal components: a new method for the analysis of genetically structured populations. BMC Genetics 11:94. doi:10.1186/1471-2156-11-94
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object
pca <- gt_pca(lobsters)
# Run clustering on the first 10 PCs
cluster_pca <- gt_cluster_pca(
x = pca,
n_pca = 10,
k_clusters = c(1, 5),
method = "kmeans",
n_iter = 1e5,
n_start = 10,
quiet = FALSE
)
# Find best K through minimum BIC
cluster_pca <- gt_cluster_pca_best_k(cluster_pca,
stat = "BIC",
criterion = "min",
quiet = FALSE
)
# Best K is stored in the object
cluster_pca$best_k
Concatenate VCF files of the same samples into a gen_tibble
Description
This function reads several VCF files with the same samples but different
loci (e.g. one file per chromosome, as distributed by many projects) into a
single gen_tibble, as bcftools concat would, followed by
gen_tibble(). It needs no space on disk beyond the gen_tibble: each file
is read twice, once for its loci and samples, and once for its genotypes,
which are written straight into the backing file of the gen_tibble. To
combine files with different samples, use gt_merge_vcfs().
Usage
gt_concat_vcfs(
files,
backingfile = NULL,
valid_alleles = c("A", "T", "C", "G"),
missing_alleles = c("0", "."),
allow_duplicates = FALSE,
names_as_int = TRUE,
chromosomes_as_int = FALSE,
n_cores = 1,
phased = FALSE,
quiet = FALSE
)
Arguments
files |
a character vector with the paths to two or more VCF files
(.vcf or .vcf.gz, which are read faster if compressed with |
backingfile |
the path, including the file name without extension, for
the backing files of the |
valid_alleles |
a vector of valid allele values; it defaults to 'A','T', 'C' and 'G'. |
missing_alleles |
a vector of values in the VCF files that are considered as missing alleles ('.' is always missing). |
allow_duplicates |
boolean: whether to allow duplicated loci (the same
chromosome and position) or duplicated loci names in the |
names_as_int |
boolean: whether the loci names are integers (the index
of each locus in the |
chromosomes_as_int |
boolean: whether the chromosomes are integer
codes rather than a factor, which saves memory with many chromosomes
(e.g. RAD loci assembled de novo); the names are written to a sidecar
file next to the backing file (see |
n_cores |
the number of cores used to decompress bgzipped files and to parse the genotypes. Defaults to 1. |
phased |
boolean: whether to store phased genotypes, giving a phased
|
quiet |
boolean: whether to omit the report of the concatenation. |
Details
As with gen_tibble(), only biallelic SNPs are read from each file. The
loci of the gen_tibble are those of the first file, followed by those of
the second file, and so on (as in bcftools concat), so the files should
be given in the order of their chromosomes. The same chromosome can be
split across several files (e.g. in chunks), but duplicated loci (the same
chromosome and position) are an error, unless allow_duplicates = TRUE.
All files must have the same samples, but they can be in a different order
in each file: the samples of the gen_tibble are in the order of the first
file, and the genotypes of the other files are reordered to match. Sample
names must be unique within each file.
As in gen_tibble(), the ploidy of each individual is estimated from the
first variants of each file; the ploidy of an individual in the
gen_tibble is its largest ploidy across files (e.g. with a file of the X
chromosome in which males are haploid, males are still diploid). Files in
which the genotypes of an individual are all missing in the first variants
are ignored for its ploidy (unless they all are).
Unlike gen_tibble(), by default (names_as_int = TRUE) the loci are
named with integers (their index in the gen_tibble), rather than with
their VCF IDs, to save memory with large datasets. With names_as_int = FALSE, loci take their VCF IDs (a missing ID '.' gives a name made of
the chromosome and the position, as in gen_tibble()).
Value
a gen_tibble with the data of all files (saved, as with
gen_tibble()).
See Also
gt_merge_vcfs() to merge VCF files with different samples.
Examples
# two VCF files with the same individuals, one for each chromosome
example_gt <- load_example_gt("gen_tbl")
vcf_chr1 <- gt_as_vcf(select_loci(example_gt, 1:4),
file = tempfile(fileext = ".vcf")
)
vcf_chr2 <- gt_as_vcf(select_loci(example_gt, 5:6),
file = tempfile(fileext = ".vcf")
)
# concatenate them, keeping the VCF IDs as loci names (by default, unlike
# gen_tibble(), loci are named with integers to save memory)
concat_gt <- gt_concat_vcfs(c(vcf_chr1, vcf_chr2),
names_as_int = FALSE,
backingfile = tempfile("concat_")
)
concat_gt
show_loci(concat_gt)
Discriminant Analysis of Principal Components for gen_tibble
Description
This function implements the Discriminant Analysis of Principal Components
(DAPC, Jombart et al. 2010). This method describes the diversity between
pre-defined groups. When groups are unknown, use gt_cluster_pca() to infer
genetic clusters. See 'details' section for a succinct description of the
method, and the vignette in the package adegenet ("adegenet-dapc") for a
tutorial.
Usage
gt_dapc(
x,
pop = NULL,
n_pca = NULL,
n_da = NULL,
loadings_by_locus = TRUE,
data = NULL,
max_missing = 0.5,
n_cores = bigstatsr::nb_cores()
)
Arguments
x |
an object of class |
pop |
either a factor indicating the group membership of individuals; or
an integer defining the desired k if x is a |
n_pca |
number of principal components to be used in the Discriminant Analysis. If NULL, k-1 will be used. |
n_da |
an integer indicating the number of axes retained in the Discriminant Analysis step. |
loadings_by_locus |
a logical indicating whether the loadings and contribution of each locus should be stored (TRUE, default) or not (FALSE). Such output can be useful, but can also create large matrices when there are a lot of loci and many dimensions. |
data |
the |
max_missing |
with a PCA of missing genotypes, the largest fraction of
missing genotypes at a locus for its loadings to be estimated (see
Details); loci with more get |
n_cores |
the number of cores used to estimate the loadings of the
loci of a PCA with missing genotypes. Default is
|
Details
The Discriminant Analysis of Principal Components (DAPC) is designed to investigate the genetic structure of biological populations. This multivariate method consists in a two-steps procedure. First, genetic data are transformed (centred, possibly scaled) and submitted to a Principal Component Analysis (PCA). Second, principal components of PCA are submitted to a Linear Discriminant Analysis (LDA). A trivial matrix operation allows to express discriminant functions as linear combination of alleles, therefore allowing one to compute allele contributions. More details about the computation of DAPC are to be found in the indicated reference.
Results can be visualised with autoplot.gt_dapc(), see the help of that
method for the available plots. There are also gt_dapc_tidiers for
manipulating the results. For the moment, this function returns objects of
class adegenet::dapc which are
compatible with methods from adegenet; graphical methods for DAPC are
documented in adegenet::scatter.dapc (see ?scatter.dapc). This is likely
to change in the future, so make sure you do not rely on the objects
remaining compatible.
This function aligns with the guidelines proposed by Thia (2023) for the
standardized application of DAPC to genotype data. Our default settings are
designed to follow these recommendations, so that the number of principal
components (n_pca) defaults to the smaller of k-1 and the number of
available principal components (where k is the number of populations or
clusters), and the number of discriminant functions (n_da) is set to the
minimum of k-1 and n_pca. The user can override these defaults by
specifying the n_pca and n_da arguments, but caution is advised when
adjusting n_pca to avoid potential overfitting. We recommend users consult
these guidelines and consider their individual dataset to ensure best
practices.
With missing genotypes, the PCA does not need imputed genotypes: the
default method of gt_pca() compares individuals over the loci genotyped
in both (as PLINK does), and the discriminant analysis uses its scores as
it would those of any PCA. The loadings of the loci (loadings_by_locus)
are then estimated by regressing the standardised genotypes of each locus
on the scores of the n_pca components (with an intercept), over the
individuals genotyped at that locus, and multiplying these coefficients by
the loadings of the discriminant functions. This needs the genotypes: give
the gen_tibble of the PCA as data. With complete genotypes, the
regression coefficients are the loadings of the PCA, so the results are
the same as with the usual matrix product. With missing genotypes, the
loadings of the PCA (which count missing genotypes as 0) would shrink loci
with many missing genotypes, and hide them in the loadings plots. Loci
with more than a fraction max_missing of their genotypes missing (by
default, more than half), or genotyped in fewer than n_pca + 1
individuals, get NA loadings: estimated from few individuals, their
loadings are noisy (the more so the fewer the individuals), and would top
the rankings of the loci. The posterior probabilities of group membership
do not account for the noisier scores of individuals with many missing
genotypes.
Note that there is no current method to predict scores for individuals not included in the original analysis. This is because we currently do not have a mechanism to store the pca information in the object, and that is needed for prediction.
Value
an object of class adegenet::dapc
References
Jombart T, Devillard S and Balloux F (2010) Discriminant analysis of principal components: a new method for the analysis of genetically structured populations. BMC Genetics 11:94. doi:10.1186/1471-2156-11-94 Thia, J. A. (2023). Guidelines for standardizing the application of discriminant analysis of principal components to genotype data. Molecular Ecology Resources, 23, 523–538. https://doi.org/10.1111/1755-0998.13706
See Also
gt_cluster_pca() gt_cluster_pca_best_k() adegenet::dapc()
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object (the lobsters have some missing genotypes, which do not
# need to be imputed)
pca <- gt_pca(lobsters)
# Run DAPC on the `gt_pca` object, providing `pop` as factor; with missing
# genotypes, the loadings of the loci need the genotypes (`data`)
populations <- as.factor(lobsters$population)
gt_dapc(pca, n_pca = 6, n_da = 2, pop = populations, data = lobsters)
# Run clustering on the first 10 PCs
cluster_pca <- gt_cluster_pca(
x = pca,
n_pca = 10,
k_clusters = c(1, 5),
method = "kmeans",
n_iter = 1e5,
n_start = 10,
quiet = FALSE
)
# Find best k
cluster_pca <- gt_cluster_pca_best_k(cluster_pca,
stat = "BIC",
criterion = "min"
)
# Run DAPC on the `gt_cluster_pca` object
gt_dapc(cluster_pca, n_pca = 10, n_da = 2, data = lobsters)
# should be stored (TRUE, default) or not (FALSE). This information is
# required to predict group membership of new individuals using predict, but
# makes the object slightly bigger.
Compute and store blocked f2 statistics for ADMIXTOOLS 2
Description
Compute and store blocked f2 statistics for ADMIXTOOLS 2
Usage
gt_extract_f2(
.x,
outdir = NULL,
blgsize = 0.05,
maxmem = 8000,
maxmiss = 0,
minmaf = 0,
maxmaf = 0.5,
minac2 = FALSE,
outpop = NULL,
outpop_scale = TRUE,
transitions = TRUE,
transversions = TRUE,
overwrite = FALSE,
adjust_pseudohaploid = NULL,
fst = TRUE,
afprod = TRUE,
poly_only = c("f2"),
apply_corr = TRUE,
n_cores = 1,
quiet = FALSE
)
Arguments
.x |
a grouped |
outdir |
Directory where data will be stored. |
blgsize |
SNP block size in Morgan. Default is 0.05 (5 cM). If |
maxmem |
Maximum amount of memory to be used. If the required amount of
memory exceeds |
maxmiss |
Discard SNPs which are missing in a fraction of populations
higher than |
minmaf |
Discard SNPs with minor allele frequency less than |
maxmaf |
Discard SNPs with minor allele frequency greater than |
minac2 |
Discard SNPs with allele count lower than 2 in any population
(default |
outpop |
Keep only SNPs which are heterozygous in this population |
outpop_scale |
Scale f2-statistics by the inverse |
transitions |
Set this to |
transversions |
Set this to |
overwrite |
Overwrite existing files in |
adjust_pseudohaploid |
Genotypes of pseudohaploid samples are usually
coded as |
fst |
Write files with pairwise FST for every population pair. Setting
this to FALSE can make |
afprod |
Write files with allele frequency products for every
population pair. Setting this to FALSE can make |
poly_only |
Specify whether SNPs with identical allele frequencies in
every population should be discarded ( |
apply_corr |
Apply small-sample-size correction when computing
f2-statistics (default |
n_cores |
Parallelize computation across |
quiet |
Suppress printing of progress updates |
Value
SNP metadata (invisibly)
References
Maier R, Patterson N (2024). admixtools: Inferring demographic history from genetic data. R package version 2.0.4, https://github.com/uqrmaie1/admixtools.
This function prepares data for various ADMIXTOOLS 2 functions from the
package ADMIXTOOLS 2. It takes a gen_tibble, computes allele
frequencies and blocked f2-statistics, and writes the results to outdir. It
is equivalent to admixtools::extract_f2(), from which its code is adapted
(admixtools is by Robert Maier, released under GPL-3).
Examples
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
lobsters <- lobsters %>% group_by(population)
f2_path <- tempfile()
gt_extract_f2(lobsters, outdir = f2_path, quiet = TRUE)
admixtools::f2_from_precomp(f2_path, verbose = FALSE)
Convert a genlight object from adegenet to a gen_tibble
Description
This function converts a genlight object from the adegenet package to a
gen_tibble object
Usage
gt_from_genlight(x, backingfile = NULL, ...)
Arguments
x |
A |
backingfile |
the path, including the file name without extension, for
backing files used to store the data (they will be given a .bk and .rds
automatically). If |
... |
Additional arguments passed to gen_tibble(). |
Details
Currently supports diploid
genlightobjects only (all values in@ploidymust be 2).Requires non-missing slots:
loc.names,n.loc,loc.all,chromosome,position,ploidy,ind.names. Thepopslot is optional; if absent, the returned gen_tibble will omit the population column.
Value
A gen_tibble object
Examples
# Create a simple genlight object
x <- new("genlight",
list(
indiv1 = c(1, 1, 0, 1, 1, 0),
indiv2 = c(2, 1, 1, 0, 0, 0)
),
ploidy = c(2, 2),
loc.names = paste0("locus", 1:6),
chromosome = c("chr1", "chr1", "chr2", "chr2", "chr3", "chr3"),
position = c(100, 200, 150, 250, 300, 400),
loc.all = c("A/T", "C/G", "G/C", "A/T", "T/C", "G/A"),
pop = c("pop1", "pop2")
)
file <- paste0(tempfile(), "gt_from_genlight")
# Convert to gen_tibble
new_gt <- gt_from_genlight(x, backingfile = file)
Get the names of files storing the genotypes of a gen_tibble
Description
A function to return the names of the files used to store data in a
gen_tibble. Specifically, this returns the .rds file storing the big
matrix (FBM) and its .bk backing file, always as the first two elements
and in this order. If the gen_tibble has integer names of loci
(names_as_int = TRUE) or integer chromosomes (chromosomes_as_int = TRUE), the sidecar files holding their original names (.loci.tsv, then
.chromosomes.tsv, see gt_lookup_loci() and gt_lookup_chromosomes())
follow. A sidecar is listed only if the gen_tibble uses it (its loci table
holds integer names, or integer chromosomes) and the file exists, so a
gen_tibble without integer names or chromosomes has exactly two files.
Usage
gt_get_file_names(x)
Arguments
x |
Value
a character vector with the names and paths of the .rds and .bk files, followed by those of any sidecar files
Examples
example_gt <- load_example_gt("gen_tbl")
# To retrieve the names of and paths to the .bk and .rds files use:
gt_get_file_names(example_gt)
Checks if a gen_tibble has been imputed
Description
This function checks if a dataset has been imputed. Note that having imputation does not mean that the imputed values are used.
Usage
gt_has_imputed(x)
Arguments
x |
a |
Value
boolean TRUE or FALSE depending on whether the dataset has been imputed
Examples
example_gt <- load_example_gt("gen_tbl")
# The initial gen_tibble contains no imputed values
example_gt %>% gt_has_imputed()
# Now impute the gen_tibble
example_gt <- example_gt %>% gt_impute_simple()
# And we can check it has been imputed
example_gt %>% gt_has_imputed()
Simple imputation based on allele frequencies
Description
This function provides a very simple imputation algorithm for gen_tibble
objects by using the mode, mean or sampling from the allele frequencies. Each
locus is imputed independently (and thus linkage information is ignored).
Usage
gt_impute_simple(x, method = c("mode", "mean0", "random"), n_cores = 1)
Arguments
x |
a gen_tibble with missing data |
method |
one of
|
n_cores |
the number of cores to be used |
Details
This function is a wrapper around bigsnpr::snp_fastImputeSimple(), which
imputes the whole file backing matrix (FBM). The allele frequencies used to
impute each locus are therefore estimated from all the individuals in the
FBM, so the gen_tibble must contain all of them (in any order). If some
individuals have been removed (e.g. with filter()), use
gt_update_backingfile() to resave the FBM with only the individuals in the
gen_tibble before imputing.
As each locus is imputed independently, the gen_tibble does not need to
contain all the loci in the FBM: the loci that have been removed (e.g. with
select_loci()) are also imputed, but they do not affect the imputation of
the loci in the gen_tibble. If only a few of the loci in the FBM are kept,
resaving the FBM with gt_update_backingfile() first avoids the time spent
imputing loci that are not used.
Value
a gen_tibble with imputed genotypes
See Also
bigsnpr::snp_fastImputeSimple() which this function wraps.
Examples
example_gt <- load_example_gt("gen_tbl")
# Impute the gen_tibble
example_gt <- example_gt %>% gt_impute_simple()
# And we can check it has been imputed
example_gt %>% gt_has_imputed()
Imputation based XGBoost
Description
This function provides a simple imputation algorithm for gen_tibble
objects based on local XGBoost models.
Usage
gt_impute_xgboost(
x,
alpha = 1e-04,
size = 200,
p_train = 0.8,
n_cor = nrow(x),
seed = NA,
n_cores = 1,
append_error = TRUE
)
Arguments
x |
a gen_tibble with missing data |
alpha |
Type-I error for testing correlations. Default is |
size |
Number of neighbour SNPs to be possibly included in the model
imputing this particular SNP. Default is |
p_train |
Proportion of non missing genotypes that are used for training
the imputation model while the rest is used to assess the accuracy of
this imputation model. Default is |
n_cor |
Number of rows that are used to estimate correlations. Default uses them all. |
seed |
An integer, for reproducibility. Default doesn't use seeds. |
n_cores |
the number of cores to be used |
append_error |
boolean, should the xgboost error estimates be appended as an attribute to the genotype column of the gen_tibble. If TRUE (the default), a matrix of two rows (the number of missing values, and the error estimate) and as many columns as the number of loci will be appended to the gen_tibble. attr(missing_gt$genotypes, "imputed_errors") |
Details
This function is a wrapper around bigsnpr::snp_fastImpute(). The error
rates from the xgboost, if appended, can be retrieved with
attr(x$genotypes, "imputed_errors") where x is the gen_tibble.
Value
a gen_tibble with imputed genotypes
See Also
bigsnpr::snp_fastImpute() which this function wraps.
Examples
example_gt <- load_example_gt("gen_tbl")
# Impute the gen_tibble
example_gt <- example_gt %>% gt_impute_xgboost()
# And we can check it has been imputed
example_gt %>% gt_has_imputed()
Load a gen_tibble
Description
Load a gen_tibble previously saved with gt_save(). If the .rds and
.bk files have not
been moved, they should be found automatically. If they were moved, use
reattach_to to point to the .rds file (the .bk file needs to be in the
same directory as the .rds file). Sidecar files with the original names
of loci and chromosomes stored as integers (.loci.tsv and
.chromosomes.tsv, see gt_lookup_loci() and gt_lookup_chromosomes())
are found next to the .bk file, so move any of them with it.
Usage
gt_load(file = NULL, reattach_to = NULL)
Arguments
file |
the file name, including the full path. If it does not end with .gt, the extension will be added. |
reattach_to |
the file name, including the full path, of the .rds file if it was moved. It assumes that the .bk file is found in the same path. You should be able to leave this to NULL unless you have moved the files. |
Value
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
# remove some individuals
example_gt_filtered <- example_gt %>% filter(id != "a")
# save the filtered gen_tibble object
backing_files <- gt_save(example_gt_filtered,
file_name = paste0(tempfile(), "_example_filtered")
)
# backing_files[1] contains the name of the saved .gt file
backing_files[1]
# To load the saved gen_tibble object, use the path to the saved .gt file
reloaded_gt <- gt_load(backing_files[1])
# And we have loaded the gt without individual "a"
reloaded_gt
Look up the original names of loci and chromosomes stored as integers
Description
With names_as_int = TRUE and chromosomes_as_int = TRUE, gen_tibble()
stores the names of the loci, and their chromosomes, as integers, to save
memory and time with large datasets (e.g. RAD loci assembled de novo, with
millions of loci, each its own "chromosome"). The original names are
written to sidecar files next to the backing file (see Details), from which
these functions get them back:
-
gt_lookup_loci()gives back the original names and chromosomes of some loci (e.g. the hits of a selection scan), without changing thegen_tibble; -
gt_lookup_chromosomes()gives back the names of chromosome codes (e.g. thechromosomecolumn of the results of window statistics or runs of homozygosity); -
gt_restore_loci()puts the original names back into the loci table of agen_tibble(e.g. once it has been filtered down to fewer loci).
Usage
gt_lookup_loci(.x, loci, check_positions = TRUE)
gt_lookup_chromosomes(.x, chromosomes)
gt_restore_loci(.x, names = TRUE, chromosomes = TRUE, check_positions = TRUE)
Arguments
.x |
a |
loci |
a subset of the loci table of |
check_positions |
boolean: whether to check that the positions of the
loci in the locus sidecar are the same as in |
chromosomes |
for |
names |
boolean: whether to restore the names of the loci (if they are integers). Default is TRUE. |
Details
The sidecars of the backing file foo.bk are:
-
foo.loci.tsv(written withnames_as_int = TRUE), with the columnsint_name,name,chromosomeandposition, and one line per locus, in increasing order of integer name. The names are those thatnames_as_int = FALSEwould give (with a missing ID replaced by the chromosome and position), and the chromosomes are their names (not their codes); -
foo.chromosomes.tsv(written withchromosomes_as_int = TRUE), with the columnsint_chromosomeandchromosome, and one line per chromosome, in increasing order of code.
Both are tab separated text files with a header, with no quotes, and "."
for missing values, so they can be read with any tool (e.g.
data.table::fread(path, quote = "") or readr::read_tsv(path, quote = "")), and joined to show_loci() by name = int_name or chromosome = int_chromosome.
The sidecars are written by gen_tibble() when it reads a VCF file with
parser = "cpp", and by gt_merge_vcfs() and gt_concat_vcfs().
Functions that write a new backing file (gt_update_backingfile(),
gt_order_loci(), rbind()) write new sidecars for it,
with the loci and chromosomes that they keep (integer names and codes keep
their values, so they still find their line). Keep the sidecars with the
other files of the gen_tibble (see gt_save()): without them, the
original names are lost.
Only the file name ties a sidecar to its data, so the position of each
locus in the locus sidecar is compared with its position in the loci
table: a different position means that the sidecar belongs to other data
(e.g. files copied by hand from different runs), and is an error. If you
changed the positions of the loci yourself (e.g. after a liftover to a new
assembly), the names in the sidecar are still right: use check_positions = FALSE. The chromosome sidecar has no positions to check.
Lookups are fast: the first lookup in a session reads through a sidecar once to index it (about a second per GB), and later lookups of a few loci only read the parts of the file that hold them.
Value
gt_lookup_loci() returns loci (as a table), with integer names
in its name column, and integer codes in its chromosome column,
replaced by their original names (as character vectors); the other
columns, and the rows and their order, are unchanged. Columns that
already hold names are left as they are, so the same code works on data
read with or without the integer options.
gt_lookup_chromosomes() returns the names of the chromosomes (a
character vector, with NA for NA). Chromosomes that are already names (a
factor or a character vector) are returned as a character vector.
gt_restore_loci() returns .x, with the original names in its loci
table (as if it had been read without the integer options: names as a
character vector, and chromosomes as a factor). The levels of the factor
are the chromosomes of the loci in .x (unused levels are dropped, as
by droplevels()), so that restoring a few loci of data with millions
of chromosomes is quick. It does not save it: use gt_save().
Examples
vcf_path <- system.file(
"extdata/anolis/punctatus_t70_s10_n46_filtered.recode.vcf.gz",
package = "tidypopgen"
)
anole_gt <- gen_tibble(vcf_path,
backingfile = tempfile("anolis_"),
names_as_int = TRUE, chromosomes_as_int = TRUE, quiet = TRUE
)
head(show_loci(anole_gt))
# the original names of the loci with the most missing genotypes
missing <- loci_missingness(anole_gt)
gt_lookup_loci(anole_gt, which(missing > 0.6))
# the same, from a subset of the loci table, with the missingness
hits <- show_loci(anole_gt) %>%
dplyr::mutate(missing = missing) %>%
dplyr::filter(missing > 0.6)
gt_lookup_loci(anole_gt, hits)
# the names of some chromosome codes
gt_lookup_chromosomes(anole_gt, c(1, 5, 5, NA))
# put the original names back into the gen_tibble
anole_gt <- gt_restore_loci(anole_gt)
head(show_loci(anole_gt))
Merge several VCF files into a gen_tibble
Description
This function reads several VCF files with different samples (e.g. one
per population, or per sequencing batch) into a single gen_tibble, as
bcftools merge would, followed by gen_tibble(). It is much faster than
reading each file with gen_tibble() and merging them with
rbind() (one pair at a time). Each file is read once:
its loci are matched across files, and its genotypes are kept in a
temporary backing file next to the merged one (one byte per genotype,
deleted at the end), then copied into the merged backing file. With little
space on disk, options(tidypopgen.merge_cache = FALSE) reads each file
twice instead (once for its loci and once for its genotypes), which is
slower but needs no space beyond the merged gen_tibble.
Usage
gt_merge_vcfs(
files,
variants = c("intersection", "union"),
missing_to_ref = FALSE,
alt_mismatch = c("drop", "split"),
ref_mismatch = c("error", "drop", "swap"),
force_samples = FALSE,
backingfile = NULL,
valid_alleles = c("A", "T", "C", "G"),
missing_alleles = c("0", "."),
allow_duplicates = FALSE,
names_as_int = TRUE,
chromosomes_as_int = FALSE,
n_cores = 1,
phased = FALSE,
quiet = FALSE
)
Arguments
files |
a character vector with the paths to two or more VCF files
(.vcf or .vcf.gz, which are read faster if compressed with |
variants |
which sites to keep: "intersection" (the default) keeps the sites found in all files; "union" keeps all sites (see details). |
missing_to_ref |
boolean: with |
alt_mismatch |
what to do with loci at the same position that have the same REF but a different ALT allele: "drop" (the default) drops the site, "split" keeps them as separate loci (see details). |
ref_mismatch |
what to do with loci at the same position that have a different REF allele: "error" (the default) stops with an error, "drop" drops the site, "swap" merges loci whose alleles are swapped, swapping their genotypes (see details). |
force_samples |
boolean: whether to allow the same sample name in different files, prefixing the duplicated names by the index of their file (see details). Defaults to FALSE. |
backingfile |
the path, including the file name without extension, for
the backing files of the merged |
valid_alleles |
a vector of valid allele values; it defaults to 'A','T', 'C' and 'G'. |
missing_alleles |
a vector of values in the VCF files that are considered as missing alleles ('.' is always missing). |
allow_duplicates |
boolean: whether to allow duplicated loci (the same
chromosome and position) or duplicated loci names in the merged
|
names_as_int |
boolean: whether the loci names are integers (the index
of each locus in the merged |
chromosomes_as_int |
boolean: whether the chromosomes are integer
codes rather than a factor, which saves memory with many chromosomes
(e.g. RAD loci assembled de novo); the names are written to a sidecar
file next to the backing file (see |
n_cores |
the number of cores used to decompress bgzipped files and to parse the genotypes. Defaults to 1. |
phased |
boolean: whether to store phased genotypes, giving a phased
|
quiet |
boolean: whether to omit the report of the merge. |
Details
As with gen_tibble(), only biallelic SNPs are read from each file. Loci
are matched across files by chromosome and position (as in bcftools merge), so chromosomes need to be named in the same way in all files (a mix
of e.g. 'chr1' and '1' would match no loci). A locus is merged with a site
at the same chromosome and position if their alleles agree: the same REF
and ALT alleles, or a missing allele (e.g. the ALT '.' of a monomorphic
locus), which takes the allele of the other files (a site with the same
alleles is preferred to one with a missing allele). Loci whose alleles do
not agree are handled as follows:
loci with the same REF but a different ALT allele (e.g. A/C and A/G):
bcftools mergewould make a multiallelic site, which agen_tibblecan not store, so by default the site is dropped (alt_mismatch = "drop"); withalt_mismatch = "split"(asbcftools merge -m none), the loci are kept as separate loci at the same position (which needsallow_duplicates = TRUE), each with missing genotypes for the samples of the other files.loci with a different REF allele (e.g. A/C and C/A): the REF allele should be the base of the reference genome at that position, so
bcftools mergestops with an error, as does this function by default (ref_mismatch = "error", listing the first few mismatches). Withref_mismatch = "drop"such sites are dropped; withref_mismatch = "swap", loci whose alleles are swapped (A/C and C/A) are merged, swapping the genotypes of the later file (as rbind() does), and other mismatches are handled as withalt_mismatch. Swapping is needed e.g. for VCF files exported by PLINK 1.9, which by default set the REF allele to the major allele.
Strands are not flipped (all VCF files are on the forward strand). Loci
at the same position within a file are never merged with each other (as in
bcftools merge); if a file has several loci at the same position (e.g. a
multiallelic site split into biallelic records, as by bcftools norm -m-),
each is merged with the site of the other files that has its alleles, if
any, before the others are handled as above.
The merged gen_tibble has the samples of the first file, followed by those
of the second file, and so on. By default (variants = "intersection"),
it keeps the sites found in all files, as rbind() does;
with variants = "union", it keeps all sites (as bcftools merge), and the
samples of the
files without a site get missing genotypes there, or homozygous reference
genotypes with missing_to_ref = TRUE (as bcftools merge -0). Sites are
ordered by chromosome (in order of first appearance across the files), then
by position.
Unlike gen_tibble(), by default (names_as_int = TRUE) the loci are
named with integers (their index in the merged gen_tibble), rather than
with their VCF IDs, to save memory with large datasets. With
names_as_int = FALSE, each locus takes its name (VCF ID) from the first
file where it is found (a missing ID '.' gives a name made of the
chromosome and the position, as in gen_tibble()).
Sample names must be unique across files: if they are not, the function
stops, unless force_samples = TRUE, in which case the duplicated names are
prefixed by the index of their file, as bcftools merge --force-samples
does (e.g. sample 'S3' of the second file becomes '2:S3').
As in gen_tibble(), the ploidy of each individual is estimated from the
first variants of its file. The individuals of different files can have
different ploidies.
Value
a gen_tibble with the merged data (saved, as with
gen_tibble()).
See Also
gt_concat_vcfs() to combine VCF files with the same samples
and different loci (e.g. one file per chromosome);
rbind() to merge two gen_tibble objects (e.g. read
from files of other formats).
Examples
vcf_a <- system.file("extdata", "pop_a.vcf", package = "tidypopgen")
vcf_b <- system.file("extdata", "pop_b.vcf", package = "tidypopgen")
# the REF and ALT alleles of some loci are swapped between these two files
# (which a VCF from PLINK can have), so we swap them back to merge them;
# we also keep the VCF IDs as loci names (by default, unlike gen_tibble(),
# loci are named with integers to save memory)
merged_gt <- gt_merge_vcfs(c(vcf_a, vcf_b),
ref_mismatch = "swap",
names_as_int = FALSE,
backingfile = tempfile("merged_")
)
merged_gt
show_loci(merged_gt)
Order the loci table of a gen_tibble
Description
This function reorders the loci table so that positions within a chromosome
are sequential. It also re-saves the genotypes into a new file backed matrix
with the new order, so that it can be used by functions such as
loci_ld_clump() and gt_pca_autoSVD(). If the loci table is already
ordered, the original gen_tibble is returned. This function will update the
backingfiles of the gen_tibble and return the gen_tibble object, use <-
as per the example provided to ensure that the names of the newly updated
backingfiles are stored in the gen_tibble object.
Usage
gt_order_loci(
.x,
use_current_table = FALSE,
ignore_genetic_dist = TRUE,
quiet = FALSE,
...
)
Arguments
.x |
|
use_current_table |
boolean, if FALSE (the default), the table will be reordered; if TRUE, then the current loci table, which might have been reordered manually, will be used, but only if the positions within each chromosome are sequential |
ignore_genetic_dist |
boolean to ignore the genetic distance when
checking (the default), so that only positions are checked. Note that, if
|
quiet |
boolean to suppress information about the files |
... |
other arguments |
Value
Examples
example_gt <- load_example_gt("gen_tbl") %>% select_loci(c(1, 5, 2, 6, 4, 3))
# Loci are in the wrong order
show_loci(example_gt)
# Reorder the loci, ignoring genetic distance
example_gt_ordered <- gt_order_loci(example_gt, ignore_genetic_dist = TRUE)
# Loci are now in the correct order
show_loci(example_gt_ordered)
Principal Component Analysis for gen_tibble objects
Description
Computes the leading principal components of the genotypes of a
gen_tibble, with one of two methods. method = "partial" (the default)
is exact and handles missing genotypes as plink --pca (PLINK 1.9) does,
without imputation; method = "random" needs complete or imputed
genotypes, but much less memory, for very large numbers of individuals.
For datasets with linkage disequilibrium, gt_pca_autoSVD() implements the
algorithm of bigsnpr, which removes regions of long-range LD and outliers.
Usage
gt_pca(
x,
k = 10,
method = c("partial", "random"),
fun_scaling = NULL,
n_cores = bigstatsr::nb_cores(),
block_size = NULL,
engine = c("auto", "blas", "internal"),
tol = 1e-04,
verbose = FALSE,
fun_prod = bigstatsr::big_prodVec,
fun_cprod = bigstatsr::big_cprodVec,
total_var = TRUE
)
Arguments
x |
a |
k |
the number of principal components to compute. Default is |
method |
|
fun_scaling |
|
n_cores |
the number of cores. With |
block_size |
for |
engine |
for |
tol |
for |
verbose |
for |
fun_prod |
for |
fun_cprod |
for |
total_var |
a boolean indicating whether to compute the total
variance, needed for the proportion of variance explained by each
component (see |
Value
a gt_pca object, which is a subclass of big_SVD; this is an S3
list with elements:
-
d, the singular values (the eigenvalues of the GRM ared^2 / m, withmthe number of loci, as given byplink --pca) -
u, the scores for each sample on each component (the left singular vectors, i.e. the eigenvectors of the GRM) -
v, the loadings (the right singular vectors; with missing genotypes and"partial",Z^T u / d, with missing genotypes as 0) -
center, the centering vector -
scale, the scaling vector -
method,"partial"or"random" -
call, the call to the function -
loci, the loci used -
square_frobenius, the total variance (withtotal_var = TRUE; with missing genotypes and"partial", the number of loci times the trace of the GRM)
Two attributes record the genotypes that the PCA was computed on:
-
imputed,TRUEif the PCA used imputed genotypes -
missing,TRUEif the genotypes had missing values (only possible with"partial")
PCAs made by earlier versions of tidypopgen do not have these
attributes; their methods needed complete or imputed genotypes.
Methods
Both methods compute the leading eigenvectors of the
genetic relationship matrix (GRM) of the standardised genotypes
z_{il} (by default z_{il} = (g_{il} - 2p_l) /
\sqrt{2p_l(1-p_l)}, with g_{il} the number of alternate alleles
and p_l their frequency):
-
"partial"computes the GRM, then its leading eigenvectors (an exact, truncated decomposition). It is the method of choice up to some tens of thousands of individuals: the GRM takes 8 bytes per pair of individuals (0.2 GB for 5,000 individuals, 3.2 GB for 20,000), and the time grows with the square of the number of individuals and linearly with the number of loci. -
"random"runsbigstatsr::big_randomSVD(), which never builds the GRM: it multiplies blocks of the genotypes by vectors until the components converge (totol), with memory linear in the numbers of individuals and loci. It is slower than"partial"(e.g. 175 s against 31 s on 1,043 individuals and 643,733 loci), but works with any number of individuals.
With complete (or imputed) genotypes, both give the singular value
decomposition of the standardised genotypes, and "partial" gives the
same results as the former gt_pca_partialSVD().
Missing genotypes
With method = "partial", missing genotypes
do not need to be imputed: as in PLINK 1.9 (plink --make-rel, which
plink --pca decomposes), each pair of individuals is compared over the
loci genotyped in both,
G_{ij} = \frac{1}{n_{ij}} \sum_l z_{il} z_{jl},
with z_{il} = 0 when g_{il} is missing, n_{ij} the
number of loci genotyped in both individuals, and allele frequencies
from the genotyped individuals. This keeps individuals with many missing
genotypes (e.g. ancient DNA) in place, whereas imputation pulls them
towards the centre of the PCA, or makes missingness an axis of its own.
The results match those of PLINK 1.9, also with very high missingness.
Imputed genotypes are used only if the gen_tibble is set to use them
(with gt_set_imputed()). Pairs of individuals with no locus genotyped
in both have no defined relationship and give an error: remove the
individuals with the most missing genotypes (see indiv_missingness()).
With missing genotypes, the GRM is not necessarily positive
semi-definite; only its largest (positive) eigenvalues are used.
With method = "random", the genotypes must be complete or imputed (see
gt_impute_simple()); imputed genotypes are used automatically when
they exist.
The PCA records which genotypes it used (see Value). With missing
genotypes, gt_pcadapt() tests each locus on the individuals genotyped
at it, and gt_dapc() estimates the loadings of the loci without
counting missing genotypes as 0 (for which it needs the gen_tibble).
Scaling
fun_scaling = NULL (the default) uses the binomial
scaling above, as bigsnpr::snp_scaleBinom() (and PLINK) do, with the
allele frequencies of the genotyped individuals. A function that returns
a centre and a scale for each locus, such as
bigsnpr::snp_scaleAlpha() or bigstatsr::big_scale(), can be used
instead. A scaling computed from the genotypes (such as these) needs
complete or imputed genotypes, and so does any scaling with "random"
(one that does not depend on the genotypes, e.g.
big_scale(center = FALSE, scale = FALSE), works with missing genotypes
with "partial"). With "partial", loci
with a zero scale (monomorphic loci) add nothing to the GRM, but are
counted in n_{ij}, as in PLINK (filter them out first); with
"random", they give an error.
Pseudohaploids
Pseudohaploid individuals (see
gt_pseudohaploid()) are coded 0 or 2, and enter the PCA as homozygous
diploids, as in PLINK and smartpca with pseudohaploid ancient DNA:
half their dosage is their allele frequency, as for diploids, while the
allele frequencies of the default scaling count one allele per
pseudohaploid (as loci_alt_freq() does). Their own entries on the
diagonal of the GRM are about twice those of diploids, which does not
change the relationships between individuals.
Speed
With method = "partial", the matrix products use either
the BLAS library that R uses (engine = "blas"), which is fastest when
it is an optimised one (OpenBLAS, MKL, Apple Accelerate), or the
vectorised products of the Eigen library in parallel on n_cores
(engine = "internal"), which do not depend on the BLAS and are many
times faster than R's reference BLAS (the default on Windows and in the
CRAN builds of R for macOS). The internal products are in single
precision for blocks of up to 1,024 loci, summed in double precision
(twice as fast; the relative error of the GRM is about 1e-7, well below
the 6 significant digits that PLINK writes). engine = "auto" times both
on a small product, once per session, and uses the faster. The number of
loci genotyped in both individuals is counted on bit-packed genotypes, as
in PLINK. On a laptop with 4 cores and OpenBLAS, 4,000 individuals and
100,000 loci with 45% missing genotypes took 32 s (62 s with PLINK 1.9),
and 1,000 individuals and 300,000 complete loci 7 s (8 s with PLINK, 11 s
with the former gt_pca_partialSVD()); with R's reference BLAS, 39 s and
12 s.
Note
Rather than accessing elements of a gt_pca object directly, it is
better to use tidy and augment. See gt_pca_tidiers.
References
Purcell S. et al. (2007) PLINK: a tool set for whole-genome association and population-based linkage analyses. American Journal of Human Genetics 81: 559-575.
Chang C.C. et al. (2015) Second-generation PLINK: rising to the challenge of larger and richer datasets. GigaScience 4: 7.
Privé F., Luu K., Blum M.G.B., McGrath J.J. and Vilhjálmsson B.J. (2020) Efficient toolkit implementing best practices for principal component analysis of population genetic data. Bioinformatics 36: 4449-4457.
See Also
pairwise_grm() with method = "plink" for the GRM itself;
gt_pca_autoSVD() for data with linkage disequilibrium.
Other gt_pca_functions:
gt_pca_autoSVD(),
gt_pca_partialSVD(),
gt_pca_randomSVD()
Examples
example_gt <- load_example_gt("gen_tbl")
# the example has missing genotypes, which are compared pairwise
gt_pca(example_gt, k = 2)
# three simulated populations, with up to 90% missing genotypes
set.seed(1)
sim_gt <- gt_simulate_bn(
n_indiv = c(20, 20, 20), n_loci = 2000, fst = 0.1,
missing = rep(seq(0, 0.9, length.out = 20), 3)
)
sim_pca <- gt_pca(sim_gt, k = 2, n_cores = 1)
autoplot(sim_pca, type = "scores")
# the random method needs complete or imputed genotypes, without
# monomorphic loci
sim_gt <- select_loci_if(sim_gt, loci_maf(genotypes) > 0)
sim_gt <- gt_impute_simple(sim_gt, method = "mode")
gt_pca(sim_gt, k = 2, method = "random")
PCA controlling for LD for gen_tibble objects
Description
This function performs Principal Component Analysis on a gen_tibble, using
a fast truncated SVD with initial pruning and then iterative removal of
long-range LD regions. This function is a wrapper for
bigsnpr::snp_autoSVD()
Usage
gt_pca_autoSVD(
x,
k = 10,
fun_scaling = bigsnpr::snp_scaleBinom(),
thr_r2 = 0.2,
use_positions = TRUE,
size = 100/thr_r2,
roll_size = 50,
int_min_size = 20,
alpha_tukey = 0.05,
min_mac = 10,
max_iter = 5,
n_cores = 1,
verbose = TRUE,
total_var = TRUE
)
Arguments
x |
a |
k |
Number of singular vectors/values to compute. Default is |
fun_scaling |
Usually this can be left unset, as it defaults to
|
thr_r2 |
Threshold over the squared correlation between two SNPs.
Default is |
use_positions |
a boolean on whether the position is used to define
|
size |
For one SNP, window size around this SNP to compute correlations. Default is 100 / thr_r2 for clumping (0.2 -> 500; 0.1 -> 1000; 0.5 -> 200). If not providing infos.pos (NULL, the default), this is a window in number of SNPs, otherwise it is a window in kb (genetic distance). I recommend that you provide the positions if available. |
roll_size |
Radius of rolling windows to smooth log-p-values. Default is
|
int_min_size |
Minimum number of consecutive outlier SNPs in order to be
reported as long-range LD region. Default is |
alpha_tukey |
Default is |
min_mac |
Minimum minor allele count (MAC) for variants to be included.
Default is |
max_iter |
Maximum number of iterations of outlier detection. Default is
|
n_cores |
Number of cores used. Default doesn't use parallelism. You may
use |
verbose |
Output some information on the iterations? Default is |
total_var |
a boolean indicating whether to compute the total variance
of the matrix. Default is |
Details
The genotypes must be complete or imputed (see gt_impute_simple();
imputed genotypes are used automatically). Missing genotypes give an
error (with a custom fun_scaling that does not depend on the
genotypes, they are only looked for in a sample of them, as in
bigsnpr).
Using gt_pca_autoSVD requires a reasonably large dataset, as the function
iteratively removes regions of long range LD. If you encounter: 'Error in
rollmean(): Parameter 'size' is too large.', roll_size exceeds the number
of variants on at least one of your chromosomes. Try reducing 'roll_size' to
avoid this error.
Value
a gt_pca object, which is a subclass of bigSVD; this is an S3
list with elements: A named list (an S3 class "big_SVD") of
-
d, the eigenvalues (singular values, i.e. as variances), -
u, the scores for each sample on each component (the left singular vectors) -
v, the loadings (the right singular vectors) -
center, the centering vector, -
scale, the scaling vector, -
method, a string defining the method (in this case 'autoSVD'), -
call, the call that generated the object. -
loci, the loci used after long range LD removal.
and the attributes imputed and missing (see gt_pca()).
Note
rather than accessing these elements directly, it is better to use
tidy and augment. See gt_pca_tidiers.
Monomorphic markers must be removed before PCA is computed. The error message 'Error: some variables have zero scaling; remove them before attempting to scale.' indicates that monomorphic markers are present.
See Also
bigsnpr::snp_autoSVD() which this function wraps.
Other gt_pca_functions:
gt_pca(),
gt_pca_partialSVD(),
gt_pca_randomSVD()
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci and impute
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
lobsters <- gt_impute_simple(lobsters, method = "mode")
show_loci(lobsters)$chromosome <- "1"
# Create PCA object, including total variance
gt_pca_autoSVD(lobsters,
k = 10,
roll_size = 20,
total_var = TRUE
)
# Change number of components and exclude total variance
gt_pca_autoSVD(lobsters,
k = 5,
roll_size = 20,
total_var = FALSE
)
PCA for gen_tibble objects by partial SVD
Description
This function is deprecated: use gt_pca(), whose default method gives the
same results on complete or imputed genotypes (it uses imputed genotypes
only if the gen_tibble is set to use them, see gt_set_imputed()), is
faster, and handles missing genotypes as PLINK does.
This function performs Principal Component Analysis on a gen_tibble, by
partial SVD through the eigen decomposition of the covariance. It works well
if the number of individuals is much smaller than the number of loci;
otherwise, gt_pca_randomSVD() is a better option. This function is a
wrapper for bigstatsr::big_SVD().
With up to a few thousand individuals, this is usually much faster than
gt_pca_randomSVD() (on 1,043 individuals and 643,733 loci, about 31 s
on one core against about 175 s). The covariance between individuals is
kept in memory, which takes 8 bytes per pair of individuals (about 0.2 GB
for 5,000 individuals, and 3.2 GB for 20,000); with many more
individuals, gt_pca_randomSVD() uses much less memory.
The genotypes are read in blocks of loci, decoded as doubles, of about
1 GB (set by options(bigstatsr.block.sizeGB)). A smaller size reduces the
memory used, at the cost of some speed: on the same data, blocks of
0.25 GB (options(bigstatsr.block.sizeGB = 0.25)) reduced the peak memory
from about 2.0 to 0.6 GB, and took about 25% longer.
Usage
gt_pca_partialSVD(
x,
k = 10,
fun_scaling = bigsnpr::snp_scaleBinom(),
total_var = TRUE
)
Arguments
x |
a |
k |
Number of singular vectors/values to compute. Default is |
fun_scaling |
Usually this can be left unset, as it defaults to
|
total_var |
a boolean indicating whether to compute the total variance
of the matrix. Default is |
Value
a gt_pca object, which is a subclass of bigSVD; this is an S3
list with elements: A named list (an S3 class "big_SVD") of
-
d, the eigenvalues (singular values, i.e. as variances), -
u, the scores for each sample on each component (the left singular vectors) -
v, the loadings (the right singular vectors) -
center, the centering vector, -
scale, the scaling vector, -
method, a string defining the method (in this case 'partialSVD'), -
call, the call that generated the object. -
square_frobenius, used to compute the proportion of variance explained by the components (optional)
Note
Rather than accessing these elements directly, it is better to use
tidy and augment. See gt_pca_tidiers.
Monomorphic markers must be removed before PCA is computed. The error message 'Error: some variables have zero scaling; remove them before attempting to scale.' indicates that monomorphic markers are present.
See Also
bigstatsr::big_SVD() which this function wraps.
Other gt_pca_functions:
gt_pca(),
gt_pca_autoSVD(),
gt_pca_randomSVD()
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci and impute
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
lobsters <- gt_impute_simple(lobsters, method = "mode")
# Create PCA object, including total variance
gt_pca_partialSVD(lobsters,
k = 10,
total_var = TRUE
)
# Change number of components and exclude total variance
gt_pca_partialSVD(lobsters,
k = 5,
total_var = FALSE
)
PCA for gen_tibble objects by randomized partial SVD
Description
This function is deprecated: use gt_pca() with method = "random", which
runs the same algorithm (and needs complete or imputed genotypes).
This function performs Principal Component Analysis on a gen_tibble,
by randomised partial SVD based on the
algorithm in RSpectra (by Yixuan Qiu and Jiali Mei).
This algorithm is linear in time in all dimensions and is very
memory-efficient. Thus, it can be used on very large big.matrices.
This function is a wrapper
for bigstatsr::big_randomSVD()
With up to a few thousand individuals, gt_pca_partialSVD() is usually
much faster: on 1,043 individuals and 643,733 loci, this function took
about 175 s on one core (with the default tol), against about 31 s for
gt_pca_partialSVD(). This algorithm is most useful when there are too
many individuals for gt_pca_partialSVD(), whose memory grows with the
square of the number of individuals. Using several cores (n_cores), or a
larger tol, also reduces its time.
Usage
gt_pca_randomSVD(
x,
k = 10,
fun_scaling = bigsnpr::snp_scaleBinom(),
tol = 1e-04,
verbose = FALSE,
n_cores = 1,
fun_prod = bigstatsr::big_prodVec,
fun_cprod = bigstatsr::big_cprodVec,
total_var = TRUE
)
Arguments
x |
a |
k |
Number of singular vectors/values to compute. Default is |
fun_scaling |
Usually this can be left unset, as it defaults to
|
tol |
Precision parameter of svds. Default is |
verbose |
Should some progress be printed? Default is |
n_cores |
Number of cores used (see |
fun_prod |
Function that takes 6 arguments (in this order):
|
fun_cprod |
Same as |
total_var |
a boolean indicating whether to compute the total variance
of the matrix. Default is |
Value
a gt_pca object, which is a subclass of bigSVD; this is
an S3 list with elements:
A named list (an S3 class "big_SVD") of
-
d, the eigenvalues (singular values, i.e. as variances), -
u, the scores for each sample on each component (the left singular vectors) -
v, the loadings (the right singular vectors) -
center, the centering vector, -
scale, the scaling vector, -
method, a string defining the method (in this case 'randomSVD'), -
call, the call that generated the object.
Note
Rather than accessing these elements directly, it is better to use
tidy and augment. See gt_pca_tidiers.
Monomorphic markers must be removed before PCA is computed. The error message 'Error: some variables have zero scaling; remove them before attempting to scale.' indicates that monomorphic markers are present.
See Also
bigstatsr::big_randomSVD() which this function wraps.
Other gt_pca_functions:
gt_pca(),
gt_pca_autoSVD(),
gt_pca_partialSVD()
Examples
vcf_path <-
system.file("extdata", "anolis",
"punctatus_t70_s10_n46_filtered.recode.vcf.gz",
package = "tidypopgen"
)
anole_gt <-
gen_tibble(vcf_path, quiet = TRUE, backingfile = tempfile("anolis_"))
# Remove monomorphic loci and impute
anole_gt <- anole_gt %>% select_loci_if(loci_maf(genotypes) > 0)
anole_gt <- gt_impute_simple(anole_gt, method = "mode")
# Create PCA object, including total variance
gt_pca_randomSVD(anole_gt, k = 10, total_var = TRUE)
pcadapt analysis on a gen_tibble object
Description
pcadapt is an algorithm that detects genetic markers under selection. It is
based on the principal component analysis (PCA) of the genotypes of the
individuals. The method is described in Luu et al. (2017). See the R package
pcadapt, which provides extensive documentation and examples.
Usage
gt_pcadapt(x, pca, k, n_cores = 1, max_missing = 0.5)
Arguments
x |
A |
pca |
a |
k |
Number of principal components to use in the analysis. |
n_cores |
Number of cores to use. |
max_missing |
the largest fraction of missing genotypes at a locus for
it to be tested (see Details); loci with more get |
Details
Internally, this function uses the snp_pcadapt function from the bigsnpr
package.
The genotypes tested are those that the PCA was computed on:
with a PCA of genotypes with missing values (the default method of
gt_pca(), which compares individuals over the loci genotyped in both, as PLINK does), the genotypes ofxwith their missing values; imputed genotypes are not used.with a PCA of complete or imputed genotypes, the imputed genotypes of
xif it has any (seegt_impute_simple(); they are used automatically), and otherwise its genotypes with their missing values.
With missing genotypes, each locus is tested on the individuals genotyped
at it, as in the pcadapt package. Loci with more than a fraction
max_missing of their genotypes missing (by default, more than half), or
genotyped in fewer than 3 individuals (the minimum for a t-score), are not
tested, and get NA statistics: with few individuals genotyped, their
t-scores have heavy tails, which the normal approximation of bigsnpr
turns into tiny p-values at the top of the rankings of the loci.
Loci with the same genotype in every individual genotyped can not be tested, and give an error.
Value
An object of subclass gt_pcadapt, a subclass of mhtest.
References
Luu, K., Bazin, E., & Blum, M. G. B. (2017). pcadapt: an R package to perform genome scans for selection based on principal component analysis. Molecular Ecology Resources, 17(1), 67–77. doi:10.1111/1755-0998.12592
See Also
bigsnpr::snp_pcadapt() which this function wraps.
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object (the lobsters have some missing genotypes, which do not
# need to be imputed)
pca <- gt_pca(lobsters)
# Create a gt_pcadapt object
gt_pcadapt(lobsters, pca, k = 2)
Set the ploidy of a gen_tibble to include pseudohaploids
Description
If a gen_tibble includes pseudohaploid data, its ploidy is set to -2 to
indicate that some individuals are coded as pseudohaploids. The ploidy of the
individuals is updated, with pseudohaploids set to 1 and diploids set to 2.
However, the dosages are not changed, meaning that pseudohaploids are still
coded as 0 or 2. If the gen_tibble is already set to pseudohaploid, running
gt_pseudohaploid will update the ploidy values again, if pseudohaploid
individuals have been removed then ploidy is reset to 2.
Usage
gt_pseudohaploid(x, test_n_loci = 10000)
Arguments
x |
a |
test_n_loci |
the number of loci to test to determine if an individual
is pseudohaploid. If there are no heterozygotes in the first |
Value
a gen_tibble object with the ploidy set to -2 and the individual
ploidy values updated to 1 or 2.
Examples
example_gt <- load_example_gt("gen_tbl")
# Detect pseudohaploids and set ploidy for the whole gen_tibble
example_gt <- example_gt %>% gt_pseudohaploid(test_n_loci = 3)
# Ploidy is now set to -2
show_ploidy(example_gt)
# Individual ploidy now varies between 1 (pseudohaploid) and 2 (diploid)
indiv_ploidy(example_gt)
Inbreeding from runs of homozygosity (F_ROH)
Description
Computes F_ROH, the proportion of the genome of each individual that is in
runs of homozygosity, from the runs found by windows_indiv_roh(). F_ROH
can be computed from the runs of at least a given length (e.g. 1, 2, 4, 8
and 16 Mb): long runs come from recent common ancestors, while short runs
also reflect older inbreeding.
Usage
gt_roh_froh(
roh,
min_length_mb = 0,
by = c("genome", "chromosome"),
genome_length = NULL
)
Arguments
roh |
an |
min_length_mb |
the smallest length of the runs to use, in Mb (default 0, i.e. all runs). With several values, F_ROH is computed for each. |
by |
whether to compute F_ROH over the whole genome ( |
genome_length |
the length of the genome, in bp (only used with |
Details
The length of the genome is, by default, the sum of the lengths of the
chromosomes, each being its largest position (as in detectRUNS); it can
be given instead with genome_length (e.g. the length of the autosomes of
the reference genome, or the length covered by the loci).
Value
a tibble with one row per individual (including those with no
runs), with the grouping variables of roh (if any), id, the column
min_length_mb if there are several values, chromosome if by = "chromosome", length_bp (the total length of the runs) and froh.
See Also
autoplot.indiv_roh() to plot F_ROH.
Examples
bed_file <- system.file("extdata", "roh", "roh_sim.bed",
package = "tidypopgen"
)
sim_gt <- gen_tibble(bed_file, backingfile = tempfile(), quiet = TRUE)
sim_roh <- windows_indiv_roh(sim_gt %>% group_by(population))
# F_ROH of each individual
gt_roh_froh(sim_roh)
# from the runs of at least 1, 2 and 4 Mb
gt_roh_froh(sim_roh, min_length_mb = c(1, 2, 4))
# on each chromosome
gt_roh_froh(sim_roh, by = "chromosome")
Islands of runs of homozygosity
Description
Finds the regions of the genome where many individuals (at least a
proportion threshold of them, overall or in each group) are in runs of
homozygosity: islands of runs of homozygosity (also called ROH hotspots),
which can point to regions under selection.
Usage
gt_roh_islands(roh, loci, threshold = 0.5, by_group = TRUE)
Arguments
roh |
an |
loci |
the loci table of the |
threshold |
the smallest proportion of individuals in a run for a locus to be in an island (default 0.5) |
by_group |
if |
Details
Islands are stretches of consecutive loci of a chromosome that are in runs
in at least threshold of the individuals (see gt_roh_loci()).
Value
a tibble with one row per island, with the grouping variables (if
counting by group), chromosome, start and end (the positions of its
first and last loci), length_bp (end - start + 1), n_loci,
first_locus and last_locus (rows of the loci table), and max_prop
and mean_prop (the largest and mean proportions of individuals in a
run over its loci)
Examples
bed_file <- system.file("extdata", "roh", "roh_sim.bed",
package = "tidypopgen"
)
sim_gt <- gen_tibble(bed_file, backingfile = tempfile(), quiet = TRUE)
sim_roh <- windows_indiv_roh(sim_gt %>% group_by(population))
# regions in runs in at least 20% of the individuals of a population
gt_roh_islands(sim_roh, show_loci(sim_gt), threshold = 0.2)
The loci in runs of homozygosity
Description
Counts, for each locus, the individuals that are in a run of homozygosity
(as found by windows_indiv_roh()), overall or in each group. Loci that
are in runs in most individuals of a population (see gt_roh_islands())
can point to regions under selection. The counts are those of the
.hom.summary file of PLINK --homozyg.
Usage
gt_roh_loci(roh, loci, by_group = TRUE)
Arguments
roh |
an |
loci |
the loci table of the |
by_group |
if |
Value
a tibble with one row per locus (and per group), with the grouping
variables (if counting by group), name, chromosome, position,
n_roh (the number of individuals in a run), n_indiv (the number of
individuals) and prop_roh (n_roh / n_indiv)
See Also
gt_roh_islands() to find the regions in runs in many
individuals, and autoplot.indiv_roh() (type = "coverage") to plot
them.
Examples
bed_file <- system.file("extdata", "roh", "roh_sim.bed",
package = "tidypopgen"
)
sim_gt <- gen_tibble(bed_file, backingfile = tempfile(), quiet = TRUE)
sim_roh <- windows_indiv_roh(sim_gt %>% group_by(population))
roh_loci <- gt_roh_loci(sim_roh, show_loci(sim_gt))
# the loci most often in runs in each population
roh_loci %>%
group_by(group) %>%
slice_max(prop_roh, n = 1, with_ties = FALSE)
Detect runs of homozygosity with detectRUNS (deprecated)
Description
This function is deprecated: use windows_indiv_roh(), which finds runs
of homozygosity as PLINK (--homozyg), with its parameters. It is kept so
that old code still gives the same results: it calls the sliding-window
algorithm of the package detectRUNS (detectRUNS::slidingRUNS.run()) on
each individual, as windows_indiv_roh() used to do. It needs detectRUNS
to be installed, and will be removed in a future version of tidypopgen.
Usage
gt_roh_window(
.x,
window_size = 15,
threshold = 0.05,
min_snp = 3,
heterozygosity = FALSE,
max_opp_window = 1,
max_miss_window = 1,
max_gap = 10^6,
min_length_bps = 1000,
min_density = 1/1000,
max_opp_run = NULL,
max_miss_run = NULL
)
Arguments
.x |
|
window_size |
the size of sliding window (number of SNP loci) (default = 15) |
threshold |
the threshold of overlapping windows of the same state (homozygous/heterozygous) to call a SNP in a RUN (default = 0.05) |
min_snp |
minimum n. of SNP in a RUN (default = 3) |
heterozygosity |
should we look for runs of heterozygosity (instead of homozygosity? (default = FALSE) |
max_opp_window |
max n. of SNPs of the opposite type (e.g. heterozygous snps for runs of homozygosity) in the sliding window (default = 1) |
max_miss_window |
max. n. of missing SNP in the sliding window (default = 1) |
max_gap |
max distance between consecutive SNP to be still considered a potential run (default = 10^6 bps) |
min_length_bps |
minimum length of run in bps (defaults to 1000 bps = 1 kbps) |
min_density |
minimum n. of SNP per kbps (defaults to 0.1 = 1 SNP every 10 kbps) |
max_opp_run |
max n. of opposite genotype SNPs in the run (optional) |
max_miss_run |
max n. of missing SNPs in the run (optional) |
Details
If the gen_tibble is grouped, then the grouping variable is
used to fill in the 'group' column (with several grouping variables,
their values are pasted with ".", e.g. pop1.F). Otherwise, the 'group'
column is filled with the same values as the 'id' column.
Value
A dataframe with RUNs of Homozygosity or Heterozygosity in the
analysed dataset, in the format of detectRUNS, with columns "group",
"id", "chrom", "nSNP", "from", "to", "lengthBps" (group: population,
breed, case/control etc.; id: individual identifier; chrom: chromosome on
which the run is located; nSNP: number of SNPs in the run; from: starting
position of the run, in bps; to: end position of the run, in bps;
lengthBps: size of the run)
References
Biscarini F, Cozzi P, Gaspa G, Marras G (2019) detectRUNS:
Detect Runs of Homozygosity and Runs of Heterozygosity in Diploid Genomes.
R package. doi:10.32614/CRAN.package.detectRUNS
See Also
detectRUNS::slidingRUNS.run() which this function wraps.
Examples
bed_file <- system.file("extdata", "roh", "roh_sim.bed",
package = "tidypopgen"
)
sim_gt <- gen_tibble(bed_file, backingfile = tempfile(), quiet = TRUE)
# deprecated: use windows_indiv_roh() instead
sim_roh <- suppressWarnings(gt_roh_window(sim_gt %>% group_by(population)))
head(sim_roh)
Save a gen_tibble
Description
Save the tibble (and update the backing files). The gen_tibble object is
saved to a file with extension .gt, together with update its .rds and
.bk files. Note that multiple .gt files can be linked to the same .rds
and .bk files; generally, this occurs when we create multiple subsets of
the data. The .gt file then stores the information on what subset of the
full dataset we are interested in, whilst the .rds and .bk file store the
full dataset. To reload a gen_tibble, you can pass the name of the .gt
file with gt_load(). The .gt file is compressed with gzip at its
fastest level, as saving the information on millions of loci with the
default level of saveRDS() is slow.
Usage
gt_save(x, file_name = NULL, quiet = FALSE)
Arguments
x |
|
file_name |
the file name, including the full path. If it does not end with .gt, the extension will be added. |
quiet |
boolean to suppress information about the files |
Details
If the names of the loci are integers (names_as_int = TRUE), their
original names are in a sidecar file next to the .bk file (.loci.tsv,
see gt_lookup_loci()); if the chromosomes are integers
(chromosomes_as_int = TRUE), their names are in another sidecar file
(.chromosomes.tsv, see gt_lookup_chromosomes()). The sidecars are
listed in the messages and in the value returned, after the .bk file.
Keep them with the other files (if you move the files, move them too, so
that gt_load() with reattach_to finds them).
Value
the file name and path of the .gt file, followed by those of the
.rds and .bk files and of any sidecar files (as given by
gt_get_file_names())
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
# remove some individuals
example_gt <- example_gt %>% filter(id != "a")
# save filtered gen_tibble object
gt_save(example_gt, file_name = paste0(tempfile(), "_example_filtered"))
Sets a gen_tibble to use imputed data
Description
This function sets or unsets the use of imputed data. For some analysis
that does not allow for missing data (e.g. PCA with
gt_pca(method = "random"), or gt_pca_autoSVD()), we have to use
imputation, but for other analysis it might be preferable to allow for
missing data (e.g. gt_pca(), loci_ld_clump() and loci_ld_prune()
handle missing genotypes, and use imputed ones only if they are set).
Usage
gt_set_imputed(x, set = NULL)
Arguments
x |
a |
set |
a boolean defining whether imputed data should be used |
Value
the gen_tibble, invisibly
Examples
example_gt <- load_example_gt("gen_tbl")
# Impute the gen_tibble
example_gt <- example_gt %>% gt_impute_simple()
# Check whether the gen_tibble uses imputed values
example_gt %>% gt_uses_imputed()
# Set the gen_tibble to use imputed values
example_gt %>% gt_set_imputed(TRUE)
# And check that the gen_tibble uses imputed values again
example_gt %>% gt_uses_imputed()
Simulate a toy dataset of unlinked loci
Description
Simulates the genotypes of a few populations at unlinked biallelic loci
under the Balding-Nichols model, and returns them as a gen_tibble. This is
a toy simulator for quick checks of methods on unlinked loci (e.g. that
a PCA separates populations, or how a statistic behaves with missing
genotypes); it is not meant for inference.
Usage
gt_simulate_bn(
n_indiv = 20,
n_loci = 1000,
fst = 0.05,
missing = 0,
freq_range = c(0.05, 0.95),
backingfile = NULL
)
Arguments
n_indiv |
the number of individuals per population: one value, or one per population. |
n_loci |
the number of loci. |
fst |
the divergence ( |
missing |
the probability that a genotype is missing: one value, or one per individual (e.g. to give individuals different missingness). |
freq_range |
the range of the (uniform) distribution of the ancestral allele frequencies. |
backingfile |
the path, without extension, of the backing files; by default a temporary file. |
Details
Each locus has an ancestral allele frequency p drawn uniformly in
freq_range. The frequency in population k is drawn from a beta
distribution with mean p and variance F_k p (1-p) (the
Balding-Nichols model, i.e. independent drift of each population from a
common ancestor, a star-shaped tree), and the genotypes of its individuals
are binomial draws of two alleles at that frequency (Hardy-Weinberg
proportions). Genotypes are then set to missing at random with
probability missing.
The model has no linkage, mutation, recombination, demographic history or tree of populations: for realistic data, simulate with the coalescent (e.g. msprime, which can be run from R with the slendr package).
All loci are placed on chromosome 1, 1,000 bp apart, but they are
independent. Some loci can be monomorphic in the sample. The genotypes are
generated in memory before being written to the backing file, so keep the
datasets small. Use set.seed() beforehand for reproducible datasets.
Value
a gen_tibble with columns id, population and genotypes.
References
Balding D.J. and Nichols R.A. (1995) A method for quantifying differentiation between populations at multi-allelic loci and its implications for investigating identity and paternity. Genetica 96: 3-12.
Baumdicker F. et al. (2022) Efficient ancestry and mutation simulation with msprime 1.0. Genetics 220: iyab229.
Petr M., Haller B.C., Ralph P.L. and Racimo F. (2023) slendr: a framework for spatio-temporal population genomic simulations on geographic landscapes. Peer Community Journal 3: e121.
Examples
set.seed(1)
# three populations of 20 individuals, 500 loci
sim_gt <- gt_simulate_bn(
n_indiv = 20, n_loci = 500, fst = c(0.02, 0.05, 0.1)
)
sim_gt
# three populations with missing genotypes, increasing from 0 to 90%
# across the individuals of each population
sim_missing <- gt_simulate_bn(
n_indiv = c(20, 20, 20), n_loci = 500, fst = 0.05,
missing = rep(seq(0, 0.9, length.out = 20), 3)
)
Run SNMF from R in tidypopgen
Description
Run SNMF from R in tidypopgen
Usage
gt_snmf(
x,
k,
project = "continue",
n_runs = 1,
alpha,
tolerance = 1e-05,
entropy = FALSE,
percentage = 0.05,
I,
iterations = 200,
ploidy = 2,
seed = -1
)
Arguments
x |
a |
k |
an integer giving the number of clusters |
project |
one of "continue", "new", and "force": "continue" stores files in the current project, "new" creates a new project, and "force" stores results in the current project even if the .geno input file has been altered, |
n_runs |
the number of runs for each k value (defaults to 1) |
alpha |
numeric snmf regularization parameter. See LEA::snmf for details |
tolerance |
numeric value of tolerance (default 0.00001) |
entropy |
boolean indicating whether to estimate cross-entropy |
percentage |
numeric value indicating percentage of masked genotypes, ranging between 0 and 1, to be used when entropy = TRUE |
I |
number of SNPs for initialising the snmf algorithm |
iterations |
numeric integer for maximum iterations (default 200) |
ploidy |
the ploidy of the input data (defaults to 2) |
seed |
the seed for the random number generator, either a vector of
length |
Details
This is a wrapper for LEA::snmf().
Value
an object of class gt_admix consisting of a list with the following
elements:
-
kthe number of clusters -
Qa matrix with the admixture proportions -
Pa matrix with the allele frequencies -
loga log of the output generated by ADMIXTURE (usually printed on the screen when running from the command line) -
cvthe masked cross-entropy (ifentropyis TRUE) -
loglikthe log likelihood of the model -
idthe id column of the inputgen_tibble(if applicable) -
groupthe group column of the inputgen_tibble(if applicable)
See Also
Examples
# run the example only if we have the package installed
example_gt <- load_example_gt("gen_tbl")
# To run SNMF on a gen_tibble:
example_gt %>% gt_snmf(
k = 1:3, project = "force", entropy = TRUE,
percentage = 0.5, n_runs = 1, seed = 1, alpha = 100
)
Update the backing matrix
Description
This functions forces a re-write of the file backing matrix to match the
gen_tibble. Individuals and loci are subsetted and reordered according to
the current state of the gen_tibble. A .gt, .bk and .rds file will be
created (and, if the names of the loci are integers, a new locus sidecar
with their original names, see gt_lookup_loci()).
Usage
gt_update_backingfile(
.x,
backingfile = NULL,
chunk_size = NULL,
rm_unsorted_dist = TRUE,
quiet = FALSE
)
Arguments
.x |
a |
backingfile |
the path, including the file name without extension, for backing files used to store the data (they will be given a .bk and .rds automatically). If left to NULL (the default), the file name will be based on the name of the current backing file. |
chunk_size |
the number of loci to process at once |
rm_unsorted_dist |
boolean to set |
quiet |
boolean to suppress information about the files |
Details
This function does not check whether the positions of your genetic loci are
sorted. To check this, and update the file backing matrix, use
gt_order_loci(). Tests for this function are in
test_gt_order_loci.R
Value
a gen_tibble with updated .gt, .bk, and .rds files
(i.e. a new File Backed Matrix)
Examples
example_gt <- load_example_gt("gen_tbl")
# Here, new backingfiles are created, but without using `<-` the object
# loaded in the R session is not updated
gt_update_backingfile(example_gt)
# Make sure to use `<-` to update the file names associated with the
# gen_tibble object loaded in the R session
example_gt <- example_gt %>% gt_update_backingfile()
Checks if a gen_tibble uses imputed data
Description
This function checks if a dataset uses imputed data. Note that it is possible to have a dataset that has been imputed but it is currently not using imputation.
Usage
gt_uses_imputed(x)
Arguments
x |
a |
Value
boolean TRUE or FALSE depending on whether the dataset is using the imputed values
Examples
example_gt <- load_example_gt("gen_tbl")
# Impute the gen_tibble
example_gt <- example_gt %>% gt_impute_simple()
# Check whether the gen_tibble uses imputed values
example_gt %>% gt_uses_imputed()
Add dendrograms to a heatmap of pairwise distances
Description
This function adds dendrograms to a heatmap of pairwise distances, generated
with heatmap_pairwise(). The heatmap must have been created with an order
function based on hclust(), and the dendrograms will be based on the same
clustering. Dendrograms can be added to the left (row) and/or top (column) of
the heatmap. Note that the heatmap needs to be formatted first, as it can not
be modified easily once the dendrogram panels have been added.
Usage
heatmap_add_dendro(
plot,
side = c("both", "left", "top"),
rel_size = 0.15,
line_color = "grey30",
line_size = 0.5
)
Arguments
plot |
A ggplot from |
side |
"left" (row dendrogram), "top" (column dendrogram), or "both". |
rel_size |
Size of the dendrogram relative to the panel (null unit). |
line_color |
Segment colour. |
line_size |
Segment linewidth. |
Details
To correctly align the dendrogram with the labels of the heatmap, we use a
gtable to insert the dendrogram panel directly adjacent to the heatmap
panel. This means that the dendrogram will be perfectly aligned with the
heatmap cells regardless of axis label width. However, manipulating
individual plots in a gtable is not easy, so the heatmap should be formatted
fully before the dendrograms are added.
Value
A heatmap_dendro object (a subclass of gtable), which auto-draws
on print() and is accepted by plot() and ggsave(), just like a
ggplot or patchwork object.
Examples
example_gt <- load_example_gt("gen_tbl")
# With a pairwise matrix:
fst_dist <- example_gt %>%
group_by(population) %>%
pairwise_pop_fst(method = "Nei87", type = "pairwise")
mat_plot <- heatmap_pairwise(fst_dist,
order = function(x) {
stats::hclust(stats::as.dist(x))
}
) +
ggplot2::scale_fill_viridis_c()
heatmap_add_dendro(mat_plot)
Pairwise distance heatmap
Description
Plot a square heatmap from either a full symmetric distance matrix or a tidy
tibble of distances. Rows and columns can optionally be reordered using
either an explicit ordering vector or a function that computes an ordering
(e.g. hierarchical clustering). Dendrograms can be added to the heatmap with
heatmap_add_dendro(). Note that any decoration (e.g. axis labels, fill
scale) should be added to the heatmap before adding dendrograms, as the
latter will modify the plot structure and make it difficult to add further
customization afterwards.
Usage
heatmap_pairwise(x, order = NULL)
Arguments
x |
A square numeric matrix OR a data.frame/tibble with 3 columns:
names1, names2, value (half-matrix representation). The tidy output of
|
order |
Optional ordering specification. Can be:
|
Value
A ggplot object.
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
# With a pairwise matrix:
fst_dist <- example_gt %>%
group_by(population) %>%
pairwise_pop_fst(method = "Nei87", type = "pairwise")
heatmap_pairwise(fst_dist)
# Explicit ordering
heatmap_pairwise(
fst_dist,
order = rev(rownames(fst_dist))
) +
ggplot2::scale_fill_viridis_c()
# Hierarchical clustering
heatmap_pairwise(
fst_dist,
order = function(x) {
stats::hclust(stats::as.dist(x), method = "complete")
}
)
# With a tidy tibble of distances:
fst_tidy <- example_gt %>%
group_by(population) %>%
pairwise_pop_fst(method = "Nei87", type = "tidy")
heatmap_pairwise(fst_tidy)
heatmap_pairwise(
fst_tidy,
order = function(x) {
stats::hclust(stats::as.dist(x))
}
)
Estimate individual observed heterozygosity
Description
Estimate observed heterozygosity (H_obs) for each individual (i.e. the
frequency of loci that are heterozygous in an individual). A locus is
heterozygous whenever the dosage of the alternate allele is neither zero
nor the individual's own ploidy, so this works for diploid, polyploid, and
mixed-ploidy gen_tibble objects alike (each individual is evaluated
against its own ploidy, so individuals of differing ploidy can be mixed
freely).
Usage
indiv_het_obs(.x, as_counts = FALSE, ...)
## S3 method for class 'tbl_df'
indiv_het_obs(.x, as_counts = FALSE, ...)
## S3 method for class 'grouped_gen_tbl'
indiv_het_obs(.x, as_counts = FALSE, ...)
## S3 method for class 'vctrs_bigSNP'
indiv_het_obs(.x, as_counts = FALSE, ...)
Arguments
.x |
a vector of class |
as_counts |
logical, if |
... |
currently unused. |
Details
On a grouped gen_tibble, heterozygosity is computed for all the
individuals in a single pass over the genotypes (it does not depend on the
groups), and returned in the order of the rows. Within a grouped
mutate() or summarise(), dplyr calls indiv_het_obs() on the
genotypes of each group in turn: this gives the same values, but reads the
genotypes once for each group. With many groups and large datasets,
compute it on the whole grouped tibble instead (e.g.
grouped_gt$het_obs <- indiv_het_obs(grouped_gt)), or before grouping.
Value
either:
a vector of heterozygosities, one per individuals in the
gen_tibblea matrix with two columns, where the first is the number of heterozygous loci for each individual and the second is the number of missing values for each individual
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% indiv_het_obs()
# For observed heterozygosity as counts:
example_gt %>% indiv_het_obs(as_counts = TRUE)
Individual inbreeding coefficient
Description
This function calculates the inbreeding coefficient for each individual based on the beta estimate from Weir and Goudet (2017).
Usage
indiv_inbreeding(.x, ...)
## S3 method for class 'gen_tbl'
indiv_inbreeding(.x, method = c("WG17"), allele_sharing_mat = NULL, ...)
## S3 method for class 'vctrs_bigSNP'
indiv_inbreeding(.x, method = c("WG17"), allele_sharing_mat = NULL, ...)
## S3 method for class 'grouped_gen_tbl'
indiv_inbreeding(
.x,
method = c("WG17"),
allele_sharing_mat = NULL,
type = c("vector", "list"),
...
)
Arguments
.x |
a vector of class |
... |
other arguments passed to specific methods, currently unused. |
method |
currently only "WG17" (for Weir and Goudet 2017). |
allele_sharing_mat |
optional and only relevant for "WG17", the matrix
of Allele Sharing returned by |
type |
only for a grouped |
Details
indiv_inbreeding() is an S3 generic, with methods for gen_tibble
objects (grouped or not) and for their genotypes column. Other packages
can add methods for their own classes (e.g. tibbles of genotype
likelihoods).
For a grouped gen_tibble, the coefficients are computed within each
group (the beta estimate is relative to the other individuals of the
group), giving the same values as
group_map(.x, ~ indiv_inbreeding(.x)), but much faster: the genotypes are
read only once, and only the pairs of individuals within each group are
compared. As for an ungrouped gen_tibble, the result has one value per
individual, in the order of the rows, so that it can be added as a column
(e.g. grouped_gt$inbreeding <- indiv_inbreeding(grouped_gt)).
The method for the genotypes column computes the matrix of allele
sharing of the individuals in the column, so that indiv_inbreeding() can
be used within dplyr verbs, e.g.
mutate(inbreeding = indiv_inbreeding(genotypes)). Within a grouped
mutate(), dplyr calls it on the individuals of each group in turn, so
it gives the same values as the method for a grouped gen_tibble, but
it reads the genotypes once for each group.
Value
a numeric vector of inbreeding coefficients, one per individual in
the order of the rows, named by the ids of the individuals (when
allele_sharing_mat is given, by its row names). For a grouped
gen_tibble, the coefficients are computed within each group (with
type = "list", deprecated, they are returned as a list of vectors, one
per group; an empty group gives an empty vector).
References
Weir, BS and Goudet J (2017) A Unified Characterization of Population Structure and Relatedness. Genetics (2017) 206:2085
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% indiv_inbreeding(method = "WG17")
Estimate individual missingness
Description
Estimate missingness for each individual (i.e. the frequency of missing genotypes in an individual).
Usage
indiv_missingness(.x, as_counts, block_size, ...)
## S3 method for class 'tbl_df'
indiv_missingness(
.x,
as_counts = FALSE,
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
indiv_missingness(
.x,
as_counts = FALSE,
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
indiv_missingness(
.x,
as_counts = FALSE,
block_size = bigstatsr::block_size(length(.x), 1),
...
)
Arguments
.x |
a vector of class |
as_counts |
boolean defining whether the count of NAs (rather than the rate) should be returned. It defaults to FALSE (i.e. rates are returned by default). |
block_size |
maximum number of loci read at once. |
... |
currently unused. |
Details
On a grouped gen_tibble, missingness is computed for all the
individuals in a single pass over the genotypes (it does not depend on the
groups), and returned in the order of the rows. Within a grouped
mutate() or summarise(), dplyr calls indiv_missingness() on the
genotypes of each group in turn: this gives the same values, but reads the
genotypes once for each group. With many groups and large datasets,
compute it on the whole grouped tibble instead (e.g.
grouped_gt$missingness <- indiv_missingness(grouped_gt)), or before
grouping.
Value
a vector of missingness, one per individuals in the
gen_tibble
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% indiv_missingness()
# For missingness as counts:
example_gt %>% indiv_missingness(as_counts = TRUE)
Return individual ploidy
Description
Returns the ploidy for each individual. On a grouped gen_tibble, the
ploidy of all the individuals is returned, in the order of the rows (it
does not depend on the groups).
Usage
indiv_ploidy(.x, ...)
## S3 method for class 'tbl_df'
indiv_ploidy(.x, ...)
## S3 method for class 'grouped_gen_tbl'
indiv_ploidy(.x, ...)
## S3 method for class 'vctrs_bigSNP'
indiv_ploidy(.x, ...)
Arguments
.x |
a |
... |
currently unused. |
Value
a vector of ploidy, one per individuals in the gen_tibble
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% indiv_ploidy()
Test if the loci table is ordered
Description
This functions checks that all SNPs in a chromosome are adjacent in the loci
table, and that positions (and, unless ignore_genetic_dist = TRUE,
genetic distances) are sorted within chromosomes. Missing positions (or
missing genetic distances, if they are checked) are an error, as the order
of those loci is unknown.
Usage
is_loci_table_ordered(
.x,
error_on_false = FALSE,
ignore_genetic_dist = TRUE,
...
)
## S3 method for class 'tbl_df'
is_loci_table_ordered(
.x,
error_on_false = FALSE,
ignore_genetic_dist = TRUE,
...
)
## S3 method for class 'vctrs_bigSNP'
is_loci_table_ordered(
.x,
error_on_false = FALSE,
ignore_genetic_dist = TRUE,
...
)
Arguments
.x |
a vector of class |
error_on_false |
logical, if |
ignore_genetic_dist |
logical, if |
... |
other arguments passed to specific methods. |
Value
TRUE if the loci are ordered, FALSE otherwise
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% is_loci_table_ordered()
Test whether a gen_tibble contains phased genotypes
Description
Phased genotypes (see phased in gen_tibble()) are recognised by the
code256 of their file backed matrix, which is identical to code_phased.
Usage
is_phased(.x)
Arguments
.x |
a |
Value
TRUE if the genotypes are phased, FALSE otherwise.
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
is_phased(example_gt)
vcf_path <- system.file("extdata", "phased_example.vcf",
package = "tidypopgen"
)
x <- gen_tibble(vcf_path,
phased = TRUE,
backingfile = tempfile("phased_"),
quiet = TRUE
)
is_phased(x)
Compute the Population Branch Statistics with block jackknife standard errors
Description
The function computes the genome-wide population branch statistics (PBS) for each combination of populations, together with its standard error estimated with a weighted block jackknife. The PBS is a measure of the genetic differentiation between one focal population and two reference populations.
Usage
jackknife_nwise_pop_pbs(.x, ...)
## S3 method for class 'gen_tbl'
jackknife_nwise_pop_pbs(
.x,
type = c("matrix", "tidy"),
fst_method = c("Hudson", "Nei87", "WC84"),
return_fst = FALSE,
block_size,
size_unit = c("snp", "cM", "bp"),
...
)
Arguments
.x |
a grouped |
... |
other arguments passed to specific methods, currently unused. |
type |
type of object to return. One of "matrix" or "tidy". Default is "matrix". "matrix" returns a dataframe where each row is a quantity (estimate, jack_estimate, se, z and n_blocks), followed by columns for each population comparison. "tidy" returns a tidy tibble where each row is one population comparison. |
fst_method |
the method to use for calculating Fst, one of 'Hudson',
'Nei87', and 'WC84'. See |
return_fst |
a logical value indicating whether to return the Fst values |
block_size |
The size of the blocks to leave out. |
size_unit |
Either "snp", "cM" or "bp". If "snp", the block size is in number of SNPs. If "cM", the block size is in centiMorgans. If "bp", the block size is in base pairs. |
Details
The genome is divided into non-overlapping blocks, which never span
more than one chromosome, and pairwise Fst (and thus PBS) is recomputed
leaving out one block at a time. The standard error is computed with the
weighted delete-m jackknife of Busing et al. (1999), where each block is
weighted by the number of loci it contains. See jackknife_stats_generic()
for details.
Value
either a data frame with the following columns:
-
quantity: the quantity reported in the row, one ofestimate(computed on all loci),jack_estimate(the bias corrected jackknife estimate),se(the jackknife standard error),z(jack_estimate/se), andn_blocks(the number of blocks used) -
fst_a.b: the Fst value for population a and b, ifreturn_fstis TRUE -
pbs_a.b.c: the PBS value for population a given b & c (there will be multiple such columns covering all 3 way combinations of populations in the groupedgen_tibbleobject) -
pbsn1_a.b.c: the normalised PBS value for population a given b & c or a tidy tibble with the following columns: -
stat_name: the name of populations used in the pbs calculation (e.g. "pbs_pop1.pop2.pop3"). If return_fst is TRUE, stat_name will also include "fst" calculations in the same column (e.g. "fst_pop1.pop2"). -
estimate,jack_estimate,se,z,n_blocks: as described above
References
Busing FMTA, Meijer E, Van Der Leeden R (1999) Delete-m jackknife for unequal m. Statistics and Computing 9:3-8.
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Calculate nwise pbs with blocks of 2 SNPs
example_gt %>%
jackknife_nwise_pop_pbs(
block_size = 2,
size_unit = "snp"
)
Compute pairwise Fst with block jackknife standard errors
Description
This function computes genome-wide pairwise Fst, together with its standard error estimated with a weighted block jackknife.
Usage
jackknife_pairwise_pop_fst(.x, ...)
## S3 method for class 'gen_tbl'
jackknife_pairwise_pop_fst(
.x,
type = c("matrix", "tidy"),
method = c("Hudson", "Nei87", "WC84"),
block_size,
size_unit = c("snp", "cM", "bp"),
...
)
Arguments
.x |
a grouped |
... |
other arguments passed to specific methods, currently unused. |
type |
type of object to return. One of "matrix" or "tidy". Default is "matrix". "matrix" returns a dataframe where each row is a quantity (estimate, jack_estimate, se, z and n_blocks), followed by columns for each pairwise population a and b comparison. "tidy" returns a tidy tibble where each row is one pairwise population a and b comparison. |
method |
the method to use for calculating Fst, one of 'Hudson',
'Nei87', and 'WC84'. See |
block_size |
The size of the blocks to leave out. |
size_unit |
Either "snp", "cM" or "bp". If "snp", the block size is in number of SNPs. If "cM", the block size is in centiMorgans. If "bp", the block size is in base pairs. |
Details
The genome is divided into non-overlapping blocks, which never span
more than one chromosome, and Fst is recomputed leaving out one block at a
time. The standard error is computed with the weighted delete-m jackknife
of Busing et al. (1999), where each block is weighted by the number of loci
it contains. Fst is computed as the ratio of the sum of the per locus
numerators and denominators, so leaving out a block is achieved by
subtracting its sums, without having to rescan the genotypes. See
jackknife_stats_generic() for details.
Value
either a data frame with the following columns:
-
quantity: the quantity reported in the row, one ofestimate(Fst computed on all loci),jack_estimate(the bias corrected jackknife estimate),se(the jackknife standard error),z(jack_estimate/se), andn_blocks(the number of blocks used) -
fst_a.b: the values for the pairwise Fst between population a and b (there will be multiple such columns if there are more than two populations) or a tidy tibble with the following columns: -
stat_name: the name of population a and b used in the pairwise Fst calculation (e.g. "fst_pop1.pop2") -
estimate,jack_estimate,se,z,n_blocks: as described above
References
Busing FMTA, Meijer E, Van Der Leeden R (1999) Delete-m jackknife for unequal m. Statistics and Computing 9:3-8.
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>%
group_by(population) %>%
jackknife_pairwise_pop_fst(
block_size = 2,
size_unit = "snp"
)
Compute Tajima's D with block jackknife standard errors
Description
This function computes genome-wide Tajima's D, together with its standard error estimated with a weighted block jackknife.
Usage
jackknife_pop_tajimas_d(.x, ...)
## S3 method for class 'gen_tbl'
jackknife_pop_tajimas_d(
.x,
type = c("matrix", "tidy", "list"),
block_size,
size_unit = c("snp", "cM", "bp"),
...
)
Arguments
.x |
a |
... |
other arguments passed to specific methods, currently unused. |
type |
type of object to return, if using grouped method. One of
"matrix", "tidy", or "list". Default is "matrix".
Data can be grouped by more than one variable: groups are then labelled
by the values of the grouping variables pasted with "." (e.g. |
block_size |
The size of the blocks to leave out. |
size_unit |
Either "snp", "cM" or "bp". If "snp", the block size is in number of SNPs. If "cM", the block size is in centiMorgans. If "bp", the block size is in base pairs. |
Details
The genome is divided into non-overlapping blocks, which never span
more than one chromosome, and Tajima's D is recomputed leaving out one
block at a time. The standard error is computed with the weighted delete-m
jackknife of Busing et al. (1999), where each block is weighted by the
number of loci it contains. Tajima's D is a function of sums across loci
(of the nucleotide diversity, the number of segregating sites, and
quantities that depend on the sample size of each locus), so leaving out
a block is achieved by subtracting its sums, without having to rescan the
genotypes. See jackknife_stats_generic() for details.
Missing genotypes are accounted for by using the number of non-missing
allele copies at each locus as its sample size, following Bailey et al.
(2025) as implemented in pixy. See pop_tajimas_d() for details. Loci
with no genotyped individuals are ignored. The variance of Tajima (1989)
is computed for the mean sample size across all loci (rounded to the
nearest integer), and the same sample size is used when leaving out each
block: recomputing the rounded mean for each block left out would make
Tajima's D jump whenever this changes the rounding (e.g. when the mean
sample size is close to x.5), which the jackknife would amplify into an
inflated standard error and a biased jackknife estimate.
Note that the variance of Tajima (1989) assumes that there is no
recombination among loci. Over a whole genome, Tajima's D is thus not
standardised: it is approximately proportional to
\hat{\theta}_\pi / \hat{\theta}_W - 1, with a factor that depends
on the sample size (about 5 for 10 allele copies, 4.2 for 20, and 3.4
for 100), and with genome-wide data its standard error is much smaller
than 1. Use the jackknife standard error, rather than the rules of thumb
used for single loci, to judge whether genome-wide Tajima's D differs
from 0, and compare groups with different sample sizes with caution. The
z score tests whether genome-wide Tajima's D differs from 0, which most
demographic histories other than a constant population size will cause.
Blocks should be larger than the extent of linkage disequilibrium, or
the standard error will be underestimated.
Value
if data is not grouped, a data frame with the following columns:
-
estimate: Tajima's D computed on all loci -
jack_estimate: the bias corrected jackknife estimate -
se: the jackknife standard error -
z: the z score (jack_estimate/se) -
n_blocks: the number of blocks used if data are grouped, either: a data frame with the following columns: -
quantity: the quantity reported in the row (estimate,jack_estimate,se,zorn_blocks, as described above) -
group: the value of the quantity for the group (there will be as many of these columns as groups in the gen_tibble, and they will be named by the grouping levels) a tidy tibble with the following columns: -
group: the name of the group -
estimate,jack_estimate,se,z,n_blocks: as described above or a list of data frames, one per group, with the same columns as for ungrouped data.
References
Busing FMTA, Meijer E, Van Der Leeden R (1999) Delete-m jackknife for unequal m. Statistics and Computing 9:3-8.
Tajima F (1989) Statistical method for testing the neutral mutation hypothesis by DNA polymorphism. Genetics 123:585-595.
Bailey N, Stevison L, Samuk K (2025) Correcting for bias in estimates of
\theta_W and Tajima's D from missing data in next-generation
sequencing. Molecular Ecology Resources, e14104.
doi:10.1111/1755-0998.14104
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Calculate Tajima's D using blocks of 2 SNPs
example_gt %>%
jackknife_pop_tajimas_d(
block_size = 2,
size_unit = "snp"
)
Estimate a block jackknife standard error from per locus estimates
Description
This function is mostly designed for developers: it is a general function to
estimate the genome-wide value of a statistic, together with its standard
error, using a weighted block jackknife. It takes a vector of per locus
estimates, and aggregates them by their mean (or a custom function),
leaving out one block of loci at a time. To compute specific quantities
directly from a gen_tibble, use the appropriate jackknife_* functions,
e.g jackknife_pairwise_pop_fst() to compute pairwise Fst.
Usage
jackknife_stats_generic(
.x,
loci_table,
operator = c("mean", "custom"),
block_size,
size_unit = c("snp", "cM", "bp"),
f = NULL,
...
)
Arguments
.x |
A vector containing the per locus estimates. |
loci_table |
a dataframe including at least a column 'chromosome', and
additionally a column 'position' if |
operator |
The operator to use to aggregate the per locus estimates.
Either "mean" or "custom" to use a custom function |
block_size |
The size of the blocks to leave out. |
size_unit |
Either "snp", "cM" or "bp". If "snp", the block size is in number of SNPs. If "cM", the block size is in centiMorgans. If "bp", the block size is in base pairs. |
f |
a custom function to use for the statistic. This function should take a vector of locus estimates and return a single value (see Details for the functions that are appropriate). Note that, for a custom function, the statistic is recomputed from scratch for every block, which is slower than using "mean". |
... |
Additional arguments to be passed to the custom operator function. |
Details
The genome is divided into non-overlapping blocks, which never span
more than one chromosome. Blocks can be defined as a number of SNPs, a
number of base pairs, or a size in centiMorgans (which requires the
'genetic_dist' column of the loci table to be filled in). Blocks in base
pairs cover positions 1 to block_size, block_size + 1 to
2 * block_size, and so on along each chromosome (as the windows of
windows_stats_generic() with step_size equal to window_size), and
blocks in centiMorgans start from a genetic distance of 0. The statistic
is then recomputed leaving out one block at a time, and the standard
error is computed with the weighted delete-m jackknife of Busing et al.
(1999), where each block is weighted by the number of loci with
non-missing values that it contains. Blocks should be larger than the
extent of linkage disequilibrium (e.g. 5 cM, or a few Mb).
The jackknife assumes that the statistic estimates a quantity that does
not change with the number of loci (such as a mean, or a ratio of sums),
and that is a smooth function of the data. A custom function f should
thus not be a sum (leaving out a block always makes a sum smaller, which
the jackknife would mistake for a bias), nor a statistic such as the
median or other quantiles, for which the jackknife does not give valid
standard errors. For the sum of the per locus estimates, use
operator = "mean", and multiply the estimates and the standard error by
the number of non-missing values.
Value
A tibble with columns: 'estimate' (the statistic computed on all loci), 'jack_estimate' (the bias corrected jackknife estimate), 'se' (the jackknife standard error), 'z' (the z score, jack_estimate/se), and 'n_blocks' (the number of blocks used).
References
Busing FMTA, Meijer E, Van Der Leeden R (1999) Delete-m jackknife for unequal m. Statistics and Computing 9:3-8.
Examples
example_gt <- load_example_gt("gen_tbl")
miss_by_locus <- loci_missingness(example_gt)
# Calculate the mean missingness and its standard error,
# using blocks of 2 SNPs
jackknife_stats_generic(miss_by_locus,
loci_table = show_loci(example_gt),
operator = "mean", block_size = 2,
size_unit = "snp"
)
Load example gen_tibble
Description
This function creates a gen_tibble object for use in examples in
documentation.
Usage
load_example_gt(
type = c("gen_tbl", "grouped_gen_tbl", "grouped_gen_tbl_sf", "gen_tbl_sf",
"gen_tbl_gen_dist")
)
Arguments
type |
a character string indicating the type of
|
Value
an example object of the class gen_tbl.
Examples
# This function creates an example gen_tibble object
example_gt <- load_example_gt("gen_tbl")
Estimate allele frequencies at each locus
Description
Allele frequencies can be estimates as minimum allele frequencies (MAF) with
loci_maf() or the frequency of the alternate allele (with
loci_alt_freq()). The latter are in line with the genotypes matrix (e.g. as
extracted by show_loci()). Most users will be in interested in the MAF,
but the raw frequencies might be useful when computing aggregated statistics.
Both loci_maf() and loci_alt_freq() have efficient methods to support
grouped gen_tibble objects. These can return a tidied tibble, a list, or a
matrix.
Usage
loci_alt_freq(
.x,
.col = "genotypes",
as_counts = FALSE,
n_cores,
block_size,
type,
...
)
## S3 method for class 'tbl_df'
loci_alt_freq(
.x,
.col = "genotypes",
as_counts = FALSE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
loci_alt_freq(
.x,
.col = "genotypes",
as_counts = FALSE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(length(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
loci_alt_freq(
.x,
.col = "genotypes",
as_counts = FALSE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
type = c("tidy", "list", "matrix"),
...
)
loci_maf(.x, .col = "genotypes", n_cores, block_size, type, ...)
## S3 method for class 'tbl_df'
loci_maf(
.x,
.col = "genotypes",
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
loci_maf(
.x,
.col = "genotypes",
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(length(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
loci_maf(
.x,
.col = "genotypes",
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
type = c("tidy", "list", "matrix"),
...
)
Arguments
.x |
a vector of class |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
as_counts |
boolean defining whether the count of alternate and valid (i.e. total number) alleles (rather than the frequencies) should be returned. It defaults to FALSE (i.e. frequencies are returned by default). |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
type |
type of object to return, if using grouped method. One of "tidy",
"list", or "matrix". Default is "tidy".
Data can be grouped by more than one variable: groups are then labelled
by the values of the grouping variables pasted with "." (e.g. |
... |
other arguments passed to specific methods, currently unused. |
Value
a vector of frequencies, one per locus, if as_counts = FALSE;
else a matrix of two columns, the count of alternate alleles and the count
valid alleles (i.e. the sum of alternate and reference). For a grouped
gen_tibble, the values of each group, as given by type: a tibble with
one row per locus and group ("tidy"), a list with one element per group
("list"), or a matrix with loci in rows and groups in columns ("matrix").
With as_counts = TRUE, the tibble has the columns n_alt and n_valid
instead of value, each element of the list is the two-column matrix of
its group, and "matrix" gives a list of two matrices, n_alt and
n_valid.
Examples
example_gt <- load_example_gt("gen_tbl")
# For alternate allele frequency
example_gt %>% loci_alt_freq()
# For alternate allele frequency per locus per population
example_gt %>%
group_by(population) %>%
loci_alt_freq()
# alternatively, return a list of populations with their frequencies
example_gt %>%
group_by(population) %>%
loci_alt_freq(type = "list")
# or a matrix with populations in columns and loci in rows
example_gt %>%
group_by(population) %>%
loci_alt_freq(type = "matrix")
# or within reframe (not recommended, as it much less efficient
# than using it directly as shown above)
library(dplyr)
example_gt %>%
group_by(population) %>%
reframe(alt_freq = loci_alt_freq(genotypes))
# For MAF
example_gt %>% loci_maf()
# For minor allele frequency per locus per population
example_gt %>%
group_by(population) %>%
loci_maf()
# alternatively, return a list of populations with their frequencies
example_gt %>%
group_by(population) %>%
loci_maf(type = "list")
# or a matrix with populations in columns and loci in rows
example_gt %>%
group_by(population) %>%
loci_maf(type = "matrix")
Get the chromosomes of loci in a gen_tibble
Description
Extract the loci chromosomes from a gen_tibble (or directly from its
genotype column).
Usage
loci_chromosomes(.x, .col = "genotypes", ...)
## S3 method for class 'tbl_df'
loci_chromosomes(.x, .col = "genotypes", ...)
## S3 method for class 'vctrs_bigSNP'
loci_chromosomes(.x, .col = "genotypes", ...)
Arguments
.x |
a |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
... |
currently unused. |
Value
a character vector of chromosomes
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% loci_chromosomes()
Test Hardy-Weinberg equilibrium at each locus
Description
Return the p-value from an exact test of HWE.
Usage
loci_hwe(.x, .col = "genotypes", ...)
## S3 method for class 'tbl_df'
loci_hwe(
.x,
.col = "genotypes",
mid_p = TRUE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
loci_hwe(
.x,
.col = "genotypes",
mid_p = TRUE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(length(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
loci_hwe(
.x,
.col = "genotypes",
mid_p = TRUE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
type = c("tidy", "list", "matrix"),
...
)
Arguments
.x |
a vector of class |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
... |
not used. |
mid_p |
boolean on whether the mid-p value should be computed. Default is TRUE, as in PLINK. |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
type |
type of object to return, if using grouped method. One of "tidy",
"list", or "matrix". Default is "tidy".
Data can be grouped by more than one variable: groups are then labelled
by the values of the grouping variables pasted with "." (e.g. |
Details
This function uses the original C++ algorithm from PLINK 1.90.
Value
a vector of probabilities from HWE exact test, one per locus. For
a grouped gen_tibble, empty groups (e.g. from
group_by(.drop = FALSE)) are NA.
Author(s)
the C++ algorithm was written by Christopher Chang for PLINK 1.90, based on original code by Jan Wigginton (the code was released under GPL3).
Examples
example_gt <- load_example_gt("gen_tbl")
# For HWE
example_gt %>% loci_hwe()
# For loci_hwe per locus per population, use reframe
example_gt %>%
group_by(population) %>%
reframe(loci_hwe = loci_hwe(genotypes))
Clump loci based on a Linkage Disequilibrium threshold
Description
This function uses clumping to remove SNPs at high LD. When used with its
default options, clumping based on MAF is similar to standard pruning (as
done by PLINK with "–indep-pairwise (size+1) 1 thr.r2", but it results in a
better spread of SNPs over the chromosome; see loci_ld_prune() for
pruning as in PLINK. The algorithm is that of bigsnpr::snp_clumping():
the loci of each chromosome are visited in order of importance (S), and a
locus is kept unless its squared correlation with a more important locus
that is kept, within the window, is above thr_r2. See
https://privefl.github.io/bigsnpr/articles/pruning-vs-clumping.html for more
information on the differences between pruning and clumping.
Usage
loci_ld_clump(.x, .col = "genotypes", ...)
## S3 method for class 'tbl_df'
loci_ld_clump(.x, .col = "genotypes", ...)
## S3 method for class 'vctrs_bigSNP'
loci_ld_clump(
.x,
.col = "genotypes",
S = NULL,
thr_r2 = 0.2,
size = 100/thr_r2,
exclude = NULL,
use_positions = TRUE,
min_shared = 2,
insufficient = c("keep", "remove"),
n_cores = 1,
return_id = FALSE,
...
)
Arguments
.x |
a |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
... |
currently not used. |
S |
A vector of loci statistics which express the importance of each SNP
(the more important is the SNP, the greater should be the corresponding
statistic). |
thr_r2 |
Threshold over the squared correlation between two SNPs.
Default is |
size |
For one SNP, window size around this SNP to compute correlations.
Default is |
exclude |
Vector of SNP indices to exclude anyway. For example, can be
used to exclude long-range LD regions (see Price2008). Another use can be
for thresholding with respect to p-values associated with |
use_positions |
boolean, if TRUE (the default), |
min_shared |
the minimum number of individuals genotyped at both loci
for their r^2 to be used. Default is |
insufficient |
what to do with pairs of loci genotyped together in
fewer than |
n_cores |
number of cores to be used |
return_id |
boolean on whether the id of SNPs to keep should be returned. It defaults to FALSE, which returns a vector of booleans (TRUE or FALSE) |
Details
Missing genotypes do not need to be imputed: as in PLINK (--r2,
--indep-pairwise), the squared correlation (r^2) of the allele counts of
two loci is computed over the individuals genotyped at both. With complete
(or imputed) genotypes, the results are those of
bigsnpr::snp_clumping(). Pairs of loci genotyped together in fewer than
min_shared individuals have no reliable r^2: by default, both loci are
kept (as in PLINK, for which r^2 is then undefined); with insufficient = "remove", the less important locus is removed, as if they were linked.
The pairs of loci whose r^2 is undefined because a locus does not vary
over the individuals genotyped at both are not linked. Imputed genotypes
are used only if the gen_tibble is set to use them (see
gt_set_imputed()).
r^2 is computed on genotypes packed as bits (64 individuals per word), as in PLINK; each chromosome is packed at once, which takes 3 bits per genotype.
Value
a boolean vector indicating whether the SNP should be kept (if 'return_id = FALSE', the default), else a vector of SNP indices to be kept (if 'return_id = TRUE')
See Also
bigsnpr::snp_clumping(), whose algorithm this function
follows; loci_ld_prune() for pruning as in PLINK.
Examples
# (the example has missing genotypes, which do not need to be imputed)
example_gt <- load_example_gt("gen_tbl")
# To return a boolean vector indicating whether the SNP should be kept
example_gt %>% loci_ld_clump()
# To return a vector of SNP indices to be kept
example_gt %>% loci_ld_clump(return_id = TRUE)
Prune loci based on a Linkage Disequilibrium threshold, as PLINK
Description
This function prunes loci in LD as plink --indep-pairwise (PLINK 1.9)
does, and returns the same loci. A window of window_size loci (or of
window_size kb, with window_in_kb = TRUE) moves along each chromosome
by step_size loci. Within each window, pairs of loci whose squared
correlation (r^2) is above thr_r2 are found in order, and the locus with
the lower minor allele frequency of each pair is removed (the later one
when their frequencies are equal), until no such pair remains. Loci with
no variance (e.g. monomorphic loci) are removed, as in PLINK; but, also as
in PLINK, a locus alone on its chromosome, or alone in the first window of
its chromosome (with a window in kb), is kept even if it has no variance.
Clumping (loci_ld_clump()) gives a better spread of loci along the
chromosomes.
Usage
loci_ld_prune(.x, .col = "genotypes", ...)
## S3 method for class 'tbl_df'
loci_ld_prune(.x, .col = "genotypes", ...)
## S3 method for class 'vctrs_bigSNP'
loci_ld_prune(
.x,
.col = "genotypes",
window_size,
step_size,
thr_r2,
window_in_kb = FALSE,
min_shared = 2,
insufficient = c("keep", "remove"),
n_cores = 1,
return_id = FALSE,
...
)
Arguments
.x |
a |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
... |
currently not used. |
window_size |
the size of the window: a number of loci (at least 2),
or, with |
step_size |
the number of loci by which the window moves (PLINK
recommends 1 with windows in kb). With a window of a number of loci, it
should not be larger than |
thr_r2 |
the threshold of r^2 above which two loci are linked (at least 0, and less than 1). |
window_in_kb |
boolean: is |
min_shared |
the minimum number of individuals genotyped at both loci
for their r^2 to be used. Default is |
insufficient |
what to do with pairs of loci genotyped together in
fewer than |
n_cores |
number of cores to be used (to read the genotypes; the pruning itself runs on one core, as in PLINK) |
return_id |
boolean on whether the id of SNPs to keep should be returned. It defaults to FALSE, which returns a vector of booleans (TRUE or FALSE) |
Details
Missing genotypes do not need to be imputed: as in PLINK, r^2 is the
squared correlation of the allele counts of two loci over the individuals
genotyped at both. Pairs of loci genotyped together in fewer than
min_shared individuals have no reliable r^2: by default, they are not
considered linked (as in PLINK, for which r^2 is then undefined); with
insufficient = "remove", the locus with the lower minor allele
frequency is removed, as if they were linked. Imputed genotypes are used
only if the gen_tibble is set to use them (see gt_set_imputed()).
Differences from PLINK: all individuals are used (PLINK uses only
founders); all chromosomes are treated as autosomes (PLINK treats the
sex chromosomes of males as haploid); and loci on chromosome "0"
(unplaced) are pruned as those of any other chromosome, whereas PLINK
ignores them and lists them in neither its .prune.in nor its
.prune.out file (so that --extract with .prune.in drops them, but
--exclude with .prune.out keeps them).
Value
a boolean vector indicating whether each locus is kept (as the
loci of plink --indep-pairwise in the .prune.in file), or a vector
of the indices of the loci kept (with return_id = TRUE)
References
Chang C.C. et al. (2015) Second-generation PLINK: rising to the challenge of larger and richer datasets. GigaScience 4: 7.
See Also
loci_ld_clump() for clumping.
Examples
# (the example has missing genotypes, which do not need to be imputed)
example_gt <- load_example_gt("gen_tbl")
# as plink --indep-pairwise 4 1 0.2
example_gt %>% loci_ld_prune(window_size = 4, step_size = 1, thr_r2 = 0.2)
# the indices of the loci kept
example_gt %>%
loci_ld_prune(window_size = 4, step_size = 1, thr_r2 = 0.2,
return_id = TRUE
)
Estimate missingness at each locus
Description
Estimate the rate of missingness at each locus. This function has an
efficient method to support grouped gen_tibble objects, which can return a
tidied tibble, a list, or a matrix.
Usage
loci_missingness(
.x,
.col = "genotypes",
as_counts = FALSE,
n_cores = bigstatsr::nb_cores(),
block_size,
type,
...
)
## S3 method for class 'tbl_df'
loci_missingness(
.x,
.col = "genotypes",
as_counts = FALSE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
loci_missingness(
.x,
.col = "genotypes",
as_counts = FALSE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(length(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
loci_missingness(
.x,
.col = "genotypes",
as_counts = FALSE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
type = c("tidy", "list", "matrix"),
...
)
Arguments
.x |
a vector of class |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
as_counts |
boolean defining whether the count of NAs (rather than the rate) should be returned. It defaults to FALSE (i.e. rates are returned by default). |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
type |
type of object to return, if using grouped method. One of "tidy",
"list", or "matrix". Default is "tidy".
Data can be grouped by more than one variable: groups are then labelled
by the values of the grouping variables pasted with "." (e.g. |
... |
other arguments passed to specific methods. |
Value
a vector of frequencies, one per locus
Examples
example_gt <- load_example_gt("gen_tbl")
# For missingness
example_gt %>% loci_missingness()
# For missingness per locus per population
example_gt %>%
group_by(population) %>%
loci_missingness()
# alternatively, return a list of populations with their missingness
example_gt %>%
group_by(population) %>%
loci_missingness(type = "list")
# or a matrix with populations in columns and loci in rows
example_gt %>%
group_by(population) %>%
loci_missingness(type = "matrix")
# or within reframe (not recommended, as it much less efficient
# than using it directly as shown above)
example_gt %>%
group_by(population) %>%
reframe(missing = loci_missingness(genotypes))
Get the names of loci in a gen_tibble
Description
Extract the loci names from a gen_tibble (or directly from its genotype
column).
Usage
loci_names(.x, .col = "genotypes", ...)
## S3 method for class 'tbl_df'
loci_names(.x, .col = "genotypes", ...)
## S3 method for class 'vctrs_bigSNP'
loci_names(.x, .col = "genotypes", ...)
Arguments
.x |
a vector of class |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
... |
currently unused. |
Value
a character vector of names
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% loci_names()
Estimate nucleotide diversity (pi) at each locus
Description
Estimate nucleotide diversity (\pi) at each locus, accounting for
missing values.
Usage
loci_pi(.x, .col = "genotypes", n_cores, block_size, type, ...)
## S3 method for class 'tbl_df'
loci_pi(
.x,
.col = "genotypes",
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
loci_pi(
.x,
.col = "genotypes",
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(length(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
loci_pi(
.x,
.col = "genotypes",
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
type = c("tidy", "list", "matrix"),
...
)
Arguments
.x |
a vector of class |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
type |
type of object to return, if using grouped method. One of "tidy",
"list", or "matrix". Default is "tidy".
Data can be grouped by more than one variable: groups are then labelled
by the values of the grouping variables pasted with "." (e.g. |
... |
other arguments passed to specific methods, currently unused. |
Details
Nucleotide diversity is estimated as
\pi = \frac{c_0 c_1}{n(n - 1)/2},
where:
-
c_0is the number of observed copies of allele 0, -
c_1is the number of observed copies of allele 1, -
n = c_0 + c_1is the total number of non-missing allele copies at the locus.
Missing values
are accommodated by computing n, c_0, and c_1 using only
non-missing genotype data. For polyploid data, each individual contributes
a number of allele copies equal to its ploidy.
This corresponds to the unbiased gene diversity estimator of
Nei and Roychoudhury (1974) and is applicable to diploid, polyploid
mixed-ploidy, and pseudohaploid gen_tibble objects alike.
Value
a vector of frequencies, one per locus
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# For pi
example_gt %>% loci_pi()
# For pi per locus per population
example_gt %>%
group_by(population) %>%
loci_pi()
# alternatively, return a list of populations with their pi
example_gt %>%
group_by(population) %>%
loci_pi(type = "list")
# or a matrix with populations in columns and loci in rows
example_gt %>%
group_by(population) %>%
loci_pi(type = "matrix")
# or within reframe (not recommended, as it much less efficient
# than using it directly as shown above)
example_gt %>%
group_by(population) %>%
reframe(pi = loci_pi(genotypes))
Find transitions
Description
Use the loci table to define which loci are transitions
Usage
loci_transitions(.x, .col = "genotypes", ...)
## S3 method for class 'tbl_df'
loci_transitions(.x, .col = "genotypes", ...)
## S3 method for class 'vctrs_bigSNP'
loci_transitions(.x, .col = "genotypes", ...)
Arguments
.x |
a vector of class |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
... |
other arguments passed to specific methods. |
Value
a logical vector defining which loci are transitions
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% loci_transitions()
Find transversions
Description
Use the loci table to define which loci are transversions
Usage
loci_transversions(.x, .col = "genotypes", ...)
## S3 method for class 'tbl_df'
loci_transversions(.x, .col = "genotypes", ...)
## S3 method for class 'vctrs_bigSNP'
loci_transversions(.x, .col = "genotypes", ...)
Arguments
.x |
a vector of class |
.col |
the column to be used when a tibble (or grouped tibble is passed directly to the function). This defaults to "genotypes" and can only take that value. There is no need for the user to set it, but it is included to resolve certain tidyselect operations. |
... |
other arguments passed to specific methods. |
Value
a logical vector defining which loci are transversions
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% loci_transversions()
Matrix with integer row/column names class
Description
Create a matrix with integer or character names for rows and columns. Integer
names are useful when dealing with very large numbers of rows or columns, as
the integer names can be stored more efficiently than character names. Whilst
this is possible for data.frames, the native matrix class only allows for
character row and column names via the dimnames attribute. Use
row_names() and col_names() to get or set the integer names, which are
stored in special attributes (int_rownames and int_colnames) on the
matrix.
Usage
matrix_int_names(data, row_names = NULL, col_names = NULL)
Arguments
data |
Matrix data or object coercible to matrix |
row_names |
Integer vector (stored as int_rownames) or character vector (stored as dimnames) |
col_names |
Integer vector (stored as int_colnames) or character vector (stored as dimnames) |
Details
This class allows you to have integer names as attributes while still being a
matrix, and provides methods for getting and setting these names. When you
create a matrix_int_names object, you can provide integer or character
vectors for row and column names. If you provide integer vectors, they will
be stored in special attributes (int_rownames and int_colnames) instead
of the standard dimnames. If you provide character vectors, they will be
stored in the standard dimnames as usual. You can also mix and match,
having integer names for rows and character names for columns, or vice versa.
Note that, since the row and column names are stored in special attributes,
you have to use row_names() and col_names() to get or set them, rather
than rownames() and colnames(), which will only return character names if
present.
Value
A matrix_int_names object
See Also
Other matrix_int_names_functions:
[.matrix_int_names(),
as.data.frame.matrix_int_names(),
col_names(),
print.matrix_int_names(),
row_names()
Examples
# Create a matrix with integer row and column names
my_mat <- matrix_int_names(matrix(1:6, nrow = 2),
row_names = c(10L, 20L),
col_names = c(100L, 200L, 300L)
)
row_names(my_mat) # returns integer row names
col_names(my_mat) # returns integer column names
A mutate method for gen_tibble objects
Description
A mutate method for gen_tibble objects
Usage
## S3 method for class 'gen_tbl'
mutate(..., deparse.level = 1)
Arguments
... |
a gen_tibble and a data.frame or tibble |
deparse.level |
an integer controlling the construction of column names. |
Value
a gen_tibble
Examples
example_gt <- load_example_gt("gen_tbl")
# Add a new column
example_gt %>% mutate(region = "East")
A mutate method for grouped gen_tibble objects
Description
A mutate method for grouped gen_tibble objects
Usage
## S3 method for class 'grouped_gen_tbl'
mutate(..., deparse.level = 1)
Arguments
... |
a gen_tibble and a data.frame or tibble |
deparse.level |
an integer controlling the construction of column names. |
Value
a grouped gen_tibble
Examples
test_gt <- load_example_gt("grouped_gen_tbl")
test_gt %>% mutate(region = "East")
test_gt <- load_example_gt("grouped_gen_tbl_sf")
test_gt %>% mutate(region = "East")
Compute the Population Branch Statistics for each combination of populations
Description
The function computes the population branch statistics (PBS) for each combination of populations at each locus. The PBS is a measure of the genetic differentiation between one focal population and two reference populations, and is used to identify outlier loci that may be under selection.
Usage
nwise_pop_pbs(.x, ...)
## S3 method for class 'gen_tbl'
nwise_pop_pbs(
.x,
type = c("tidy", "matrix"),
fst_method = c("Hudson", "Nei87", "WC84"),
return_fst = FALSE,
...
)
Arguments
.x |
A grouped |
... |
other arguments passed to specific methods, currently unused. |
type |
type of object to return. One of "tidy" or "matrix". Default is "tidy". |
fst_method |
the method to use for calculating Fst, one of 'Hudson',
'Nei87', and 'WC84'. See |
return_fst |
A logical value indicating whether to return the Fst values
along with the PBS values. Default is |
Value
Either a matrix_int_names with locus ID as row names (use
row_names() to retrieve them, as they can be integers) and the following
columns:
-
pbs_a.b.c: the PBS value for population a given b & c (there will be multiple such columns covering all 3 way combinations of populations in the groupedgen_tibbleobject) -
pbsn1_a.b.c: the normalized PBS value for population a given b & c. -
fst_a.b: the Fst value for population a and b, ifreturn_fstis TRUE or a tidy tibble with the following columns: -
loci: the locus ID -
stat_name: the name of populations used in the pbs calculation (e.g. "pbs_pop1.pop2.pop3"). If return_fst is TRUE, stat_name will also include "fst" calculations in the same column (e.g. "fst_pop1.pop2"). -
value: the pbs value for the populations
References
Yi X, et al. (2010) Sequencing of 50 human exomes reveals adaptation to high altitude. Science 329: 75-78.
Examples
example_gt <- load_example_gt()
# We can compute the PBS for all populations using "Hudson" method
example_gt %>%
group_by(population) %>%
nwise_pop_pbs(fst_method = "Hudson")
Compute the joint site frequency spectrum of all populations
Description
Compute the multidimensional (joint) site frequency spectrum (SFS) of all
the populations of a grouped gen_tibble, i.e. the number of loci with
each combination of numbers of copies of the derived (or minor) allele
in the populations (the "multiSFS" of easySFS and fastsimcoal2).
Missing genotypes are dealt with as in easySFS, by projecting each
population down to n_proj allele copies (see pop_sfs() for details).
Only the loci with at least n_proj called allele copies in every
population are used. A folded spectrum is folded on the total number of
copies across all populations (as in dadi).
Usage
nwise_pop_sfs(.x, ...)
## S3 method for class 'gen_tbl'
nwise_pop_sfs(
.x,
n_proj = NULL,
folded = TRUE,
ancestral = NULL,
type = c("tidy", "array"),
fastest = c("last", "first"),
max_cells = 1e+07,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
Arguments
.x |
a grouped |
... |
other arguments passed to specific methods, currently unused. |
n_proj |
the number of allele copies to project each population to:
either a single value used for all populations, a vector with one value
per population (in the order of the groups), or a vector named with the
group labels. If |
folded |
boolean, whether to fold the spectrum (the default, as the
ancestral allele is not usually known). If |
ancestral |
the ancestral allele of each locus, used to polarise
unfolded spectra: either the name of a column of the loci table (see
|
type |
the type of object to return, either "tidy" (the default) or "array". |
fastest |
the order of the cells in the tidy output: "last" (the
default) keeps the order of the populations, so that the rows are sorted
by the number of allele copies in the first population, then in the
second, and so on (the number of copies in the last population changes
fastest, as in the files written by |
max_cells |
the maximum number of cells of the spectrum; an error is raised for larger spectra, to avoid running out of memory. |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
Details
Populations are in the order of the groups (see dplyr::group_keys()):
to change their order (which matters for dadi and fastsimcoal2),
change the order of the levels of the grouping variable (e.g. with
factor()); to use a subset of the populations, filter()
the gen_tibble (empty groups are dropped). The spectrum has
prod(n_proj + 1) cells, which grows quickly with the number of
populations.
Value
If type = "tidy", a tibble with one row per cell of the joint
spectrum, with one column per population (named with the group labels)
giving its number of copies of the derived (or minor) allele (see
allele_count in pop_sfs()),
n_sites (the projected number of sites) and masked (whether the cell
is masked, see pop_sfs()). The projection of each population is
stored in the attribute n_proj. If type = "array", an sfs object
(see pop_sfs()), an array with one dimension per population.
See Also
pop_sfs(), pairwise_pop_sfs(), pop_sfs_preview()
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
example_gt %>% nwise_pop_sfs(n_proj = 2)
# the first population changing fastest
example_gt %>% nwise_pop_sfs(n_proj = 2, fastest = "first")
Compute the Pairwise Allele Sharing Matrix for a gen_tibble object
Description
This function computes the Allele Sharing matrix. Estimates Allele Sharing
(equivalent to the quantity estimated by hierfstat::matching()) between
pairs of individuals (for each locus, gives 1 if the two individuals are
homozygous for the same allele, 0 if they are homozygous for a different
allele, and 1/2 if at least one individual is heterozygous. Matching is the
average of these 0, 1/2 and 1s)
Usage
pairwise_allele_sharing(x, ...)
## S3 method for class 'tbl_df'
pairwise_allele_sharing(
x,
as_matrix = FALSE,
block_size = bigstatsr::block_size(nrow(x)),
n_cores = bigstatsr::nb_cores(),
...
)
## S3 method for class 'vctrs_bigSNP'
pairwise_allele_sharing(
x,
as_matrix = FALSE,
block_size = bigstatsr::block_size(length(x)),
n_cores = bigstatsr::nb_cores(),
...
)
Arguments
x |
a |
... |
other arguments passed to specific methods, currently unused. |
as_matrix |
boolean, determining whether the results should be a square symmetrical matrix (TRUE), or a tidied tibble (FALSE, the default) |
block_size |
maximum number of loci read at once. Genotypes are compared in a compact bit-packed form, so this has little effect on memory use. |
n_cores |
number of cores to be used, it defaults to
|
Details
Imputed genotypes are used if x is set to use them (see
gt_set_imputed()), and treated as missing otherwise.
pairwise_allele_sharing() is an S3 generic. The method for a
gen_tibble computes the matrix with the method for its genotypes
column (of class vctrs_bigSNP), and labels it with the id of the
individuals; grouping is ignored. Other packages can add methods for their
own classes of genotypes (e.g. genotype likelihoods).
Value
a matrix of allele sharing between all pairs of individuals (the diagonal is the allele sharing of each individual with itself, 1 minus half its proportion of heterozygous loci), or a tidy tibble
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
# Compute allele sharing between individuals
example_gt %>% pairwise_allele_sharing(as_matrix = FALSE)
# Alternatively, return as a tibble
example_gt %>% pairwise_allele_sharing(as_matrix = TRUE)
Compute the Genetic Distances between individuals of a gen_tibble object
Description
This function computes the genetic distance between each pair of
individuals, as ngsDist (Vieira et al. 2016) does from genotypes: at each
locus genotyped in both individuals, a score of their two genotypes, 0 for
the same genotype, 0.5 for a homozygote and a heterozygote, and 1 for
opposite homozygotes, averaged over the loci, then corrected for
saturation (by default -\log(1 - d), ngsDist's
default). The distances can be used to build trees, e.g. neighbour-joining
trees with the package ape (see the examples).
Usage
pairwise_dist(x, ...)
## S3 method for class 'tbl_df'
pairwise_dist(x, as_matrix = FALSE, ...)
## S3 method for class 'vctrs_bigSNP'
pairwise_dist(
x,
as_matrix = FALSE,
score = c("genotype", "nucleotide"),
correction = c("log", "none", "jc"),
block_size = bigstatsr::block_size(length(x)),
n_cores = bigstatsr::nb_cores(),
...
)
Arguments
x |
a |
... |
other arguments passed to specific methods, currently unused. |
as_matrix |
boolean, determining whether the results should be a square symmetrical matrix (TRUE), or a tidied tibble (FALSE, the default) |
score |
the scores of the pairs of genotypes: "genotype" (the
default), 0 for the same genotype, 0.5 for a homozygote and a
heterozygote, 1 for opposite homozygotes; or "nucleotide", the same but
0.5 for two heterozygotes (ngsDist's |
correction |
the correction of the distances d for saturation
(ngsDist's |
block_size |
maximum number of loci read at once. Genotypes are compared in a compact bit-packed form, so this has little effect on memory use. |
n_cores |
number of cores to be used, it defaults to
|
Details
Imputed genotypes are used if x is set to use them (see
gt_set_imputed()), and treated as missing otherwise.
pairwise_dist() is an S3 generic. The method for a gen_tibble
computes the matrix with the method for its genotypes column (of class
vctrs_bigSNP), and labels it with the id of the individuals; grouping
is ignored. Other packages can add methods for their own classes of
genotypes (e.g. genotype likelihoods).
Value
a tidy tibble with one row per pair of individuals (columns
item1, item2, value, the distance, and n_loci, the number of loci
genotyped in both), or, with as_matrix = TRUE, a square matrix of the
distances (0 on the diagonal) with the numbers of loci of each pair as
attribute n_loci. Pairs without any locus genotyped in both have NA
distances.
The distance and its corrections
With the default score = "genotype", the uncorrected distance d of a
pair is the proportion of their alleles that are not shared identical by
state (at each locus, 0, 1 or 2 of their 2 alleles differ): 1 - d is the proportion of pairwise_ibs(). With score = "nucleotide"
(ngsDist's --avg_nuc_dist), two heterozygotes also score 0.5, and d is
the probability that an allele drawn at random from each individual
differs: 1 - d is the allele sharing of
pairwise_allele_sharing() (whose diagonal, the allele sharing of an
individual with itself, is not 1: the distance of an individual to itself
is 0 here, as in ngsDist).
A proportion is bounded (at most 1), so it saturates: the more two
individuals have diverged, the less each further change adds to it.
Tree-building methods such as neighbour joining and minimum evolution
assume that distances are additive (the distance between two individuals
is the sum of the lengths of the branches that join them), and a saturated
distance makes the long paths, and so the deep branches, too short. The
corrections stretch the large distances. All three have the form
-b \log(1 - d / b), where b is the ceiling that
d would reach between individuals that have diverged without limit:
"log" (the default, ngsDist's): b = 1,
-\log(1 - d), minus the logarithm of the proportion of alleles shared. The logarithm turns a similarity that falls by the same factor in each generation into a distance that grows linearly with time; it is the transformation of Reynolds et al.'s (1983) coancestry distance-\log(1 - \theta), which grows linearly with the generations since two populations split (divided by twice their size) when drift alone acts in populations of constant size. ngsDist's code gives this reason: distances additive under a constant population size, as neighbour joining and minimum evolution assume. For the alleles shared by two individuals it is a heuristic, not derived from a model of mutation: it only assumes that the alleles shared would fall to none with unlimited divergence."jc": b = 3/4, Jukes and Cantor's (1969) correction for nucleotide sequences, where any base is equally likely to replace any other, so that unrelated sequences differ at 3/4 of their sites. It fits d as a divergence per nucleotide, over all the positions sequenced; on polymorphic loci alone, each with two alleles, its ceiling has no meaning, and d can reach 0.75 (
NA, with a warning)."none": d itself (the p-distance; b infinite), the easiest to interpret.
For small d the three agree: -b \log(1 - d / b) \approx d + d^2 /
(2b), so the log correction
increases a small d by a fraction of about d / 2, and a large d by more:
to 0.105 for d = 0.1 (5% more), 0.357 for d = 0.3 (19%), 0.693 for d = 0.5
(39%), and to infinity for d = 1 (opposite homozygotes at every locus;
Inf, with a warning). The corrections keep the order of the distances,
so heatmaps look alike and the nearest individuals stay the nearest; they
change the lengths of the branches of trees and, where distances are
large, can change their topology.
References
Vieira, F. G., Lassalle, F., Korneliussen, T. S., Fumagalli, M. (2016). Improving the estimation of genetic distances from next-generation sequencing data. Biological Journal of the Linnean Society, 117(1), 139-149.
Reynolds, J., Weir, B. S., Cockerham, C. C. (1983). Estimation of the coancestry coefficient: basis for a short-term genetic distance. Genetics, 105(3), 767-779.
Jukes, T. H., Cantor, C. R. (1969). Evolution of protein molecules. In H. N. Munro (Ed.), Mammalian Protein Metabolism (pp. 21-132). Academic Press.
See Also
pairwise_ibs(), pairwise_allele_sharing()
Examples
example_gt <- load_example_gt("gen_tbl")
# the distances, log corrected
pairwise_dist(example_gt)
# the average nucleotide distance, uncorrected
pairwise_dist(example_gt, score = "nucleotide", correction = "none")
# a neighbour-joining tree
dist_matrix <- pairwise_dist(example_gt, as_matrix = TRUE)
if (requireNamespace("ape", quietly = TRUE)) {
tree <- ape::nj(stats::as.dist(dist_matrix))
plot(tree, type = "unrooted")
}
Compute the Genomic Relationship Matrix for a gen_tibble object
Description
This function computes the Genomic Relationship Matrix (GRM), with one of two estimators.
Usage
pairwise_grm(
x,
allele_sharing_mat = NULL,
block_size = bigstatsr::block_size(nrow(x)),
n_cores = bigstatsr::nb_cores(),
method = c("WG17", "plink")
)
Arguments
x |
a |
allele_sharing_mat |
optional, the matrix of Allele Sharing returned by
|
block_size |
the size of the blocks to use for the computation of the
allele sharing matrix (with |
n_cores |
number of cores to be used for the computation of the
allele sharing matrix, it defaults to |
method |
the estimator: |
Details
With method = "WG17" (the default), the GRM is estimated by computing the
pairwise kinship coefficients (coancestries) between all pairs of
individuals from a matrix of Allele Sharing following the approach of Weir
and Goudet 2017 based on beta estimators). The GRM is twice the coancestry
matrix (e.g. as estimated by hierfstat::beta.dosage() with inb=FALSE).
Every locus has the same weight, and relatedness is measured relative to
the average pair of individuals.
With method = "plink", the GRM is the variance-standardised relationship
matrix of PLINK 1.9 (plink --make-rel), the matrix whose eigenvectors are
the principal components of plink --pca and of gt_pca():
G_{ij} = \sum_l z_{il} z_{jl} / n_{ij}, with standardised genotypes
z_{il} = (g_{il} - 2p_l) / \sqrt{2p_l(1-p_l)} (so that rare variants
count more), missing genotypes set to 0, and n_{ij} the number of
loci genotyped in both individuals. Pairs with no locus genotyped in both
are NaN. See gt_pca() for details.
Value
a matrix of GR between all pairs of individuals
See Also
hierfstat::beta.dosage(), gt_pca()
Examples
example_gt <- load_example_gt("gen_tbl")
# Compute the GRM from the allele sharing matrix
example_gt %>% pairwise_grm()
# To calculate using a precomputed allele sharing matrix, use:
allele_sharing <- example_gt %>% pairwise_allele_sharing(as_matrix = TRUE)
example_gt %>% pairwise_grm(allele_sharing_mat = allele_sharing)
# The variance-standardised matrix of PLINK 1.9, as used by gt_pca()
example_gt %>% pairwise_grm(method = "plink")
Compute the Identity by State Matrix for a gen_tibble object
Description
This function computes the IBS matrix.
Usage
pairwise_ibs(x, ...)
## S3 method for class 'tbl_df'
pairwise_ibs(
x,
as_matrix = FALSE,
type = c("proportion", "adjusted_counts", "raw_counts"),
block_size = bigstatsr::block_size(nrow(x)),
n_cores = bigstatsr::nb_cores(),
missing_correction = c("flat", "allele_freq"),
allele_freqs = NULL,
...
)
## S3 method for class 'vctrs_bigSNP'
pairwise_ibs(
x,
as_matrix = FALSE,
type = c("proportion", "adjusted_counts", "raw_counts"),
block_size = bigstatsr::block_size(length(x)),
n_cores = bigstatsr::nb_cores(),
missing_correction = c("flat", "allele_freq"),
allele_freqs = NULL,
...
)
Arguments
x |
a |
... |
other arguments passed to specific methods, currently unused. |
as_matrix |
boolean, determining whether the results should be a square symmetrical matrix (TRUE), or a tidied tibble (FALSE, the default) |
type |
one of:
|
block_size |
maximum number of loci read at once. Genotypes are compared in a compact bit-packed form, so this has little effect on memory use. |
n_cores |
number of cores to be used, it defaults to
|
missing_correction |
the correction for missing genotypes, for
"proportion" and "adjusted_counts": "flat" (the default, as PLINK 1.9
with the |
allele_freqs |
only used if |
Details
Note that monomorphic sites are currently considered (as in PLINK). Remove
monomorphic sites before running pairwise_ibs() if this is a concern.
Imputed genotypes are used if x is set to use them (see
gt_set_imputed()), and treated as missing otherwise.
Each pair of individuals is compared only on the loci genotyped in both.
Two corrections for missing genotypes are available (missing_correction),
which give the same values when no genotypes are missing:
"flat" (the default), as PLINK 1.9 with the
flat-missingmodifier (--distance ibs flat-missingfor "proportion",--distance flat-missingfor "adjusted_counts"): all loci have the same weight, so the number of alleles that differ between individualsiandj,d_ij, is scaled up byn_loci / n_ij, wheren_ijis the number of loci genotyped in both ("adjusted_counts"), and "proportion" is1 - d_ij / (2 * n_ij)."allele_freq", as PLINK 1.9's default (
--distance ibsand--distance): loci are weighted by their expected contribution to the distance, which depends on their allele frequencyp. Under Hardy-Weinberg equilibrium, the expected number of alleles that differ between two individuals at a locus is4 * p * (1 - p) * (p^2 - p + 1), and PLINK usesw = p * (1 - p) * (p^2 - p + 1)as the weight of the locus (0 for monomorphic loci). "adjusted_counts" is thend_ij * W / W_ij, whereWis the sum of the weights of all loci andW_ijthat of the loci genotyped in both individuals, and "proportion" is1 - adjusted_counts / (2 * n_loci). AsW / W_ijdepends on which loci are genotyped in both individuals, "adjusted_counts" can exceed2 * n_loci(and "proportion" can be negative) for pairs genotyped in both mostly at loci with small weights (loci with a rare allele), as in PLINK. For example, with two loci with frequencies 0.1 and 0.5, a pair of opposite homozygotes at the first locus, missing at the second, has "adjusted_counts" of about 6.58 (more than2 * n_loci = 4). As in PLINK, the weights are scaled to sum to just under2^32and rounded to integers (so values are identical to PLINK's),W_ijexcludes each locus missing in either individual or in both (its weight is removed once), and monomorphic loci have no weight (a missing genotype at a monomorphic locus does not change the distance, but the locus still counts inn_loci). PLINK 1.9 computes the allele frequencies from the founders only (unless--nonfoundersis used), or reads them with--read-freq;pairwise_ibs()computes them from all individuals ofx(the same as PLINK when all individuals are founders, as in data without a pedigree), unless they are given withallele_freqs(e.g. from the founders, withloci_alt_freq()). Loci without any genotype have a frequency of 0.5, as in PLINK. PLINK's1-ibsmodifier (--distance 1-ibs, written to a.mdistfile) gives1 - proportionwith either correction.
Pairs of individuals without any locus genotyped in both (or, with
"allele_freq", without any polymorphic locus genotyped in both) have
NaN (or Inf) values.
pairwise_ibs() is an S3 generic. The method for a gen_tibble
computes the matrix with the method for its genotypes column (of class
vctrs_bigSNP), and labels it with the id of the individuals; grouping
is ignored. Other packages can add methods for their own classes of
genotypes (e.g. genotype likelihoods).
Value
for "proportion" and "adjusted_counts", a tidy tibble with one row
per pair of individuals (columns item1, item2 and value), or a
square matrix if as_matrix = TRUE; for "raw_counts", a list of two
bigstatsr::FBM matrices, ibs (the counts of alleles identical by
state) and valid_n (the counts of non-missing alleles, i.e. twice the
number of loci genotyped in both individuals).
Examples
example_gt <- load_example_gt("gen_tbl")
pairwise_ibs(example_gt, type = "proportion")
# Alternatively, return a matrix
pairwise_ibs(example_gt, type = "proportion", as_matrix = TRUE)
# Adjust block_size
pairwise_ibs(example_gt, block_size = 2)
# Change type
pairwise_ibs(example_gt, type = "adjusted_counts")
pairwise_ibs(example_gt, type = "raw_counts")
# PLINK 1.9's default correction for missing genotypes
pairwise_ibs(example_gt,
type = "adjusted_counts",
missing_correction = "allele_freq"
)
Compute the KING-robust Matrix for a gen_tibble object
Description
This function computes the KING-robust estimator of kinship, reimplementing the KING algorithm of Manichaikul et al. (2010).
Usage
pairwise_king(x, ...)
## S3 method for class 'tbl_df'
pairwise_king(
x,
as_matrix = FALSE,
block_size = bigstatsr::block_size(nrow(x)),
n_cores = bigstatsr::nb_cores(),
...
)
## S3 method for class 'vctrs_bigSNP'
pairwise_king(
x,
as_matrix = FALSE,
block_size = bigstatsr::block_size(length(x)),
n_cores = bigstatsr::nb_cores(),
...
)
## S3 method for class 'grouped_df'
pairwise_king(
x,
as_matrix = FALSE,
block_size = bigstatsr::block_size(nrow(x)),
n_cores = bigstatsr::nb_cores(),
...
)
Arguments
x |
a |
... |
other arguments passed to specific methods, currently unused. |
as_matrix |
boolean, determining whether the results should be a square symmetrical matrix (TRUE), or a tidied tibble (FALSE, the default) |
block_size |
maximum number of loci read at once. Genotypes are compared in a compact bit-packed form, so this has little effect on memory use. |
n_cores |
number of cores to be used, it defaults to
|
Details
Imputed genotypes are used if x is set to use them (see
gt_set_imputed()), and treated as missing otherwise.
pairwise_king() is an S3 generic. The method for a gen_tibble
computes the matrix with the method for its genotypes column (of class
vctrs_bigSNP), and labels it with the id of the individuals. Other
packages can add methods for their own classes of genotypes (e.g. genotype
likelihoods).
For a grouped gen_tibble, kinship is computed within each group (e.g.
within each population), giving the same results as
group_map(x, ~ pairwise_king(.x)), but much faster: the genotypes are
read only once, and only the pairs of individuals within each group are
compared. With as_matrix = TRUE, the result is a list of matrices, one
per group in the order of dplyr::group_keys() (an empty group gives an
empty matrix); otherwise, it is a tibble with the pairs of individuals of
all groups, preceded by a group column (or by one column per grouping
variable, if there are several).
Value
a square symmetrical matrix of relationship coefficients between
individuals if as_matrix is TRUE, or a tidied tibble of coefficients if
as_matrix is FALSE. For a grouped gen_tibble, a list of matrices
(one per group), or a tidied tibble of the pairs within each group, with
the group columns first.
References
Manichaikul, A. et al. (2010) Robust relationship inference in genome-wide association studies. Bioinformatics, 26(22), 2867–2873. https://doi.org/10.1093/bioinformatics/btq559.
Note that monomorphic sites are currently considered. Remove monomorphic sites before running pairwise_king if this is a concern.
Examples
example_gt <- load_example_gt("gen_tbl")
# Compute the KING-robust matrix
pairwise_king(example_gt, as_matrix = TRUE)
# Or return a tidy tibble
pairwise_king(example_gt, as_matrix = FALSE)
# Adjust block_size
pairwise_king(example_gt, block_size = 2)
# Kinship within each population
example_gt %>%
group_by(population) %>%
pairwise_king()
Compute pairwise population Fst
Description
This function computes pairwise Fst. The following methods are implemented:
'Hudson': Hudson's formulation, as derived in Bhatia et al (2013) for diploids. This is the only method that can also be used with pseudohaploid data.
'Nei87' : Fst according to Nei (1987) - includes the correction for heterozygosity when computing Ht (it uses the same formulation as in
hierfstat::pairwise.neifst()),'WC84' : Weir and Cockerham (1984), correcting for missing data (it uses the same formulation as in
hierfstat::pairwise.WCfst()).
Usage
pairwise_pop_fst(.x, ...)
## S3 method for class 'gen_tbl'
pairwise_pop_fst(
.x,
type = c("tidy", "pairwise"),
by_locus = FALSE,
by_locus_type = c("tidy", "matrix", "list"),
method = c("Hudson", "Nei87", "WC84"),
return_num_dem = FALSE,
n_cores = bigstatsr::nb_cores(),
...
)
Arguments
.x |
a grouped |
... |
other arguments passed to specific methods, currently unused. |
type |
type of object to return One of "tidy" or "pairwise" for a
pairwise matrix of populations. Default is "tidy". If data are grouped by
more than one variable, the "tidy" output has one column per grouping
variable for each population of a pair (e.g. |
by_locus |
boolean, determining whether Fst should be returned by locus(TRUE), or as a single genome wide value obtained by taking the ratio of the mean numerator and denominator (FALSE, the default). |
by_locus_type |
type of object to return. One of "tidy", "matrix" or "list". Default is "tidy". |
method |
one of 'Hudson', 'Nei87', and 'WC84' |
return_num_dem |
returns a list of numerators and denominators for each locus. This is useful for creating windowed estimates of Fst (as we need to compute the mean numerator and denominator within each window). Default is FALSE. |
n_cores |
number of cores to be used, it defaults to
|
Details
For all formulae, the genome wide estimate is obtained by taking the ratio of the mean numerators and denominators over all relevant SNPs.
Loci with no genotypes in one of the two populations of a pair
(e.g. loci that failed in all the individuals of a population) carry no
information on the differentiation between them, so they are dropped for
that pair with all methods: their Fst by locus is NaN, and they do not
contribute to the mean numerator and denominator of the genome wide
estimate.
Difference from hierfstat for 'WC84': hierfstat::pairwise.WCfst()
(and hierfstat::wc()) keep these loci. Their among-population variance
component (\sigma^2_a, the numerator) is set to 0, while their
within-population components (\sigma^2_b and \sigma^2_w,
estimated from the one population with data) still add to the
denominator. So hierfstat gives these loci an Fst of 0 rather than
NaN, and its genome wide estimate is pulled towards 0 (i.e. it is
usually lower than the one computed here).
The two estimates are identical when every locus has data in both
populations, or if such loci are removed before using hierfstat. This
applies to every function that computes Fst with 'WC84' (e.g.
windows_pairwise_pop_fst(), jackknife_pairwise_pop_fst() and
nwise_pop_pbs()). 'Nei87' gives the same results as
hierfstat::pairwise.neifst(), which also drops these loci.
Value
if type=tidy, a tibble of genome-wide pairwise Fst values with
each pairwise combination as a row if "by_locus=FALSE", else a list
including the tibble of genome-wide values as well as a matrix with
pairwise Fst by locus with loci as rows and and pairwise combinations as
columns. If type=pairwise, a matrix of genome-wide pairwise Fst values is
returned.
References
Bhatia G, Patterson N, Sankararaman S, Price AL. (2013) Estimating and Interpreting FST: The Impact of Rare Variants. Genome Research, 23(9):1514–1521.
Nei, M. (1987) Molecular Evolutionary Genetics. Columbia University Press
Weir, B. S., & Cockerham, C. C. (1984). Estimating F-statistics for the analysis of population structure. Evolution, 38(6): 1358–1370.
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
# For a basic global pairwise Fst calculation:
example_gt %>%
group_by(population) %>%
pairwise_pop_fst(method = "Nei87")
# With a pairwise matrix:
example_gt %>%
group_by(population) %>%
pairwise_pop_fst(method = "Nei87", type = "pairwise")
# To calculate Fst by locus:
example_gt %>%
group_by(population) %>%
pairwise_pop_fst(method = "Hudson", by_locus = TRUE)
Compute the joint site frequency spectrum of each pair of populations
Description
Compute the two-dimensional (joint) site frequency spectrum (SFS) of each
pair of populations, i.e. the number of loci with i copies of the
derived (or minor) allele in the first population and j in the
second. Missing genotypes are dealt with as in easySFS, by projecting
each population down to n_proj allele copies (see pop_sfs() for
details). Each spectrum only uses the loci that have at least n_proj
called allele copies in both its populations, so its marginal spectra are
not, in general, equal to the spectra computed by pop_sfs(). A folded
spectrum is folded on the total number of copies across the two
populations (as in dadi), so that it counts copies of the allele that
is the minor one across the pair.
Usage
pairwise_pop_sfs(.x, ...)
## S3 method for class 'gen_tbl'
pairwise_pop_sfs(
.x,
n_proj = NULL,
folded = TRUE,
ancestral = NULL,
type = c("tidy", "array"),
fastest = c("last", "first"),
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
Arguments
.x |
a grouped |
... |
other arguments passed to specific methods, currently unused. |
n_proj |
the number of allele copies to project each population to:
either a single value used for all populations, a vector with one value
per population (in the order of the groups), or a vector named with the
group labels. If |
folded |
boolean, whether to fold the spectrum (the default, as the
ancestral allele is not usually known). If |
ancestral |
the ancestral allele of each locus, used to polarise
unfolded spectra: either the name of a column of the loci table (see
|
type |
the type of object to return, either "tidy" (the default) or "array". |
fastest |
the order of the cells of each spectrum in the tidy
output: "last" (the default) keeps the order of the populations, so
that the rows are sorted by the number of allele copies in the first
population, then in the second (the number of copies in the second
population changes fastest, as in the files written by |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
Value
If type = "tidy", a tibble with one row per cell of the joint
spectrum of each pair of populations, with the columns:
the groups of the pair (e.g.
population_1andpopulation_2; one column per grouping variable for each population of the pair, if the data are grouped by more than one variable);-
allele_count_1andallele_count_2: the number of copies of the derived (or minor) allele in the first and second population (seeallele_countinpop_sfs()); -
n_sites: the (projected) number of sites; -
masked: whether the cell is masked (seepop_sfs()).
The projection of each population is stored in the attribute n_proj.
The tibble has class pairwise_sfs_tbl, and can be plotted with
autoplot().
If type = "array", a list of sfs objects (one per pair, named with
the labels of the two groups pasted with "."), each an array with the
first population in the rows and the second in the columns (see
pop_sfs()). Pairs are in the order given by utils::combn().
See Also
pop_sfs(), nwise_pop_sfs(), pop_sfs_preview()
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
example_gt %>% pairwise_pop_sfs(n_proj = 2)
# as arrays
example_gt %>% pairwise_pop_sfs(n_proj = 2, type = "array")
Encoding of phased genotypes in a gen_tibble
Description
Phased diploid genotypes (read with phased = TRUE in gen_tibble()) are
stored in the same file backed matrix (a bigstatsr::FBM.code256) as
unphased ones, using one byte per genotype:
Usage
code_phased
phased_bytes
Format
code_phased is a numeric vector of length 256. phased_bytes is
an integer matrix with 256 rows (bytes 0 to 255) and two columns (hap1
and hap2).
Details
| byte | genotype | dosage (code256) |
| 0 | 0|0 | 0 |
| 1 | 0|1 | 1 |
| 2 | 1|1 | 2 |
| 3 | missing | NA |
| 4 | 1|0 | 1 |
Bytes 0 to 3 have the same meaning as in unphased diploid data (where byte 3
is the missing value), so that code that reads or writes the raw bytes keeps
working; only the second orientation of a heterozygote (1|0) uses a new
byte. The code256 of the matrix, code_phased, translates each byte into
a dosage, so that all functions that decode genotypes through code256 see
phased data as ordinary unphased dosages. code_phased is also how phased
data are recognised (is_phased()): it differs from the codes used for
unphased (bigsnpr::CODE_012), imputed (bigsnpr::CODE_IMPUTE_PRED) and
dosage (bigsnpr::CODE_DOSAGE) data, as it is the only one that decodes
byte 4 as 1.
phased_bytes gives, for each byte, the alleles carried by the first and
second haplotype of an individual (NA for missing, and for bytes that are
not used).
See Also
gen_tibble(), is_phased(), show_haplotypes()
Examples
code_phased[1:6]
phased_bytes[1:6, ]
Compute population specific FIS
Description
This function computes population specific FIS, using either the approach of
Nei 1987 (with an algorithm equivalent to the one used by
hierfstat::basic.stats()) or of Weir and Goudet 2017 (with an algorithm
equivalent to the one used by hierfstat::fis.dosage()).
Usage
pop_fis(
.x,
method = c("Nei87", "WG17"),
by_locus = FALSE,
include_global = FALSE,
allele_sharing_mat = NULL,
n_cores = bigstatsr::nb_cores()
)
Arguments
.x |
a grouped |
method |
one of "Nei87" (based on Nei 1987, eqn 7.41) or "WG17" (for Weir and Goudet 2017) to compute FIS |
by_locus |
boolean, determining whether FIS should be returned by locus(TRUE), or as a single genome wide value (FALSE, the default). Note that this is only relevant for "Nei87", as "WG17" always returns a single value. |
include_global |
boolean determining whether, besides the population
specific estimates, a global estimate should be appended. Note that this
will return a vector of n populations plus 1 (the global value), or a
matrix with n+1 columns if |
allele_sharing_mat |
optional and only relevant for "WG17", the matrix
of Allele Sharing returned by |
n_cores |
number of cores to be used, it defaults to
|
Value
a vector of population specific fis (plus the global value if
include_global=TRUE)
References
Nei M. (1987) Molecular Evolutionary Genetics. Columbia University Press.
Weir, BS and Goudet J (2017) A Unified Characterization of Population Structure and Relatedness. Genetics (2017) 206:2085
See Also
hierfstat::basic.stats() hierfstat::fis.dosage()
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Compute FIS using Nei87:
example_gt %>% pop_fis(method = "Nei87")
# Compute FIS using WG17:
example_gt %>% pop_fis(method = "WG17")
# To include the global FIS, set include_global = TRUE:
example_gt %>% pop_fis(method = "Nei87", include_global = TRUE)
# To return FIS by locus, set by_locus = TRUE:
example_gt %>% pop_fis(method = "Nei87", by_locus = TRUE)
# To calculate from a pre-computed allele sharing matrix:
allele_sharing_mat <- pairwise_allele_sharing(example_gt, as_matrix = TRUE)
example_gt %>% pop_fis(
method = "WG17", allele_sharing_mat =
allele_sharing_mat
)
Compute population specific Fst
Description
This function computes population specific Fst, using the approach in Weir
and Goudet 2017 (as computed by hierfstat::fst.dosage()).
Usage
pop_fst(.x, include_global = FALSE, allele_sharing_mat = NULL)
Arguments
.x |
a grouped |
include_global |
boolean determining whether, besides the population specific Fst, a global Fst should be appended. Note that this will return a vector of n populations plus 1 (the global value) |
allele_sharing_mat |
optional, the matrix of Allele Sharing returned by
|
Value
a vector of population specific Fst (plus the global value if
include_global=TRUE)
References
Weir, BS and Goudet J (2017) A Unified Characterization of Population Structure and Relatedness. Genetics (2017) 206:2085
See Also
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Compute FIS using Nei87
example_gt %>% pop_fst()
# To include the global Fst, set include_global = TRUE
example_gt %>% pop_fst(include_global = TRUE)
# To calculate from a pre-computed allele sharing matrix:
allele_sharing_mat <- pairwise_allele_sharing(example_gt, as_matrix = TRUE)
example_gt %>% pop_fst(allele_sharing_mat = allele_sharing_mat)
Compute basic population global statistics
Description
This function computes basic population global statistics, following the notation in Nei 1987 (which in turn is based on Nei and Chesser 1983):
observed heterozygosity (
\hat{h}_o, column headerHo)expected heterozygosity, also known as gene diversity (
\hat{h}_s,Hs)total heterozygosity (
\hat{h}_t,Ht)genetic differentiation between subpopulations (
D_{st},Dst)corrected total population diversity (
h'_t,Htp)corrected genetic differentiation between subpopulations (
D'_{st},Dstp)-
\hat{F}_{ST}(column header,Fst) corrected
\hat{F'}_{ST}(column headerFstp)-
\hat{F}_{IS}(column header,Fis) Jost's
\hat{D}(column header,Dest)
Usage
pop_global_stats(.x, by_locus = FALSE, n_cores = bigstatsr::nb_cores())
Arguments
.x |
a |
by_locus |
boolean, determining whether the statistics should be returned by locus(TRUE), or as a single genome wide value (FALSE, the default). |
n_cores |
number of cores to be used, it defaults to
|
Details
We use the notation of Nei 1987. That notation was for loci with
m alleles, but in our case we only have two alleles, so m=2.
Within population observed heterozygosity
\hat{h}_ofor a locus withmalleles is defined as:
\hat{h}_o= 1-\sum_{k=1}^{s} \sum_{i=1}^{m} \hat{X}_{kii}/s
where
\hat{X}_{kii}represents the proportion of homozygoteiin the sample for thekth population and
sthe number of populations,
following equation 7.38 in Nei(1987) on pp.164.
Within population expected heterozygosity (gene diversity)
\hat{h}_sfor a locus withmalleles is defined as:
\hat{h}_s=(\tilde{n}/(\tilde{n}-1))[1-\sum_{i=1}^{m}\bar{\hat{x}_i^2}-\hat{h}_o/2\tilde{n}]
#nolint where
\tilde{n}=s/\sum_k 1/n_k(i.e the harmonic mean ofn_k) and
\bar{\hat{x}_i^2}=\sum_k \hat{x}_{ki}^2/s
following equation 7.39 in Nei(1987) on pp.164.Total heterozygosity (total gene diversity)
\hat{h}_tfor a locus withmalleles is defined as:
\hat{h}_t = 1-\sum_{i=1}^{m} \bar{\hat{x}_i^2} + \hat{h}_s/(\tilde{n}s) - \hat{h}_o/(2\tilde{n}s)
where
\hat{x}_i=\sum_k \hat{x}_{ki}/s
following equation 7.40 in Nei(1987) on pp.164.
The amount of gene diversity among samples
D_{ST}is defined as:
D_{ST} = \hat{h}_t - \hat{h}_s
following the equation provided in the text at the top of page 165 in Nei(1987).The corrected amount of gene diversity among samples
D'_{ST}is defined as:
D'_{ST} = (s/(s-1))D'_{ST}
following the equation provided in the text at the top of page 165 in Nei(1987).Total corrected heterozygosity (total gene diversity)
\hat{h}_tis defined as:
\hat{h'}_t = \hat{h}_s + D'_{ST}
following the equation provided in the text at the top of page 165 in Nei(1987).-
\hat{F}_{IS}is defined as:
\hat{F}_{IS} = 1 - \hat{h}_o/\hat{h}_s
following equation 7.41 in Nei(1987) on pp.164.
-
\hat{F}_{ST}is defined as:
\hat{F}_{ST} = 1 - \hat{h}_s/\hat{h}_t = D_{ST}/\hat{h}_t
following equation 7.43 in Nei(1987) on pp.165.
-
\hat{F'}_{ST}is defined as:
\hat{F'}_{ST} = D'_{ST}/\hat{h'}_t
following the explanation provided in the text at the top of page 165 in Nei(1987). Jost's
\hat{D}is defined as:
\hat{D} = (s/(s-1))((\hat{h'}_t-\hat{h}_s)/(1-\hat{h}_s))
as defined by Jost(2008)All these statistics are first computed by locus, and then averaged across loci (including any monomorphic locus) to obtain genome-wide values. The function uses the same algorithm as
hierfstat::basic.stats()but is optimized for speed and memory usage.
Value
a tibble of population statistics, with populations as rows and statistics as columns
References
Nei M, Chesser R (1983) Estimation of fixation indexes and gene diversities. Annals of Human Genetics, 47, 253-259.
Nei M. (1987) Molecular Evolutionary Genetics. Columbia University Press, pp. 164-165.
Jost L (2008) GST and its relatives do not measure differentiation. Molecular Ecology, 17, 4015-4026.
See Also
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Compute population global statistics
example_gt %>% pop_global_stats()
# To return by locus, set by_locus = TRUE
example_gt %>% pop_global_stats(by_locus = TRUE)
Compute the population expected heterozygosity
Description
This function computes expected population heterozygosity (also referred to as gene diversity, to avoid the potentially misleading use of the term "expected" in this context), using the formula of Nei (1987).
Usage
pop_het_exp(
.x,
by_locus = FALSE,
include_global = FALSE,
n_cores = bigstatsr::nb_cores()
)
pop_gene_div(
.x,
by_locus = FALSE,
include_global = FALSE,
n_cores = bigstatsr::nb_cores()
)
Arguments
.x |
a |
by_locus |
boolean, determining whether Hs should be returned by locus(TRUE), or as a single genome wide value (FALSE, the default). |
include_global |
boolean determining whether, besides the population
specific estimates, a global estimate should be appended. Note that this
will return a vector of n populations plus 1 (the global value), or a
matrix with n+1 columns if |
n_cores |
number of cores to be used, it defaults to
|
Details
Within population expected heterozygosity (gene diversity)
\hat{h}_s for a locus with m alleles is defined as:
\hat{h}_s=\tilde{n}/(\tilde{n}-1)[1-\sum_{i}^{m}\bar{\hat{x}_i^2}-\hat{h}_o/2\tilde{n}]
#nolint
where
\tilde{n}=s/\sum_k 1/n_k (i.e the harmonic mean of
n_k) and
\bar{\hat{x}_i^2}=\sum_k \hat{x}_{ki}^2/s
following equation 7.39 in Nei(1987) on pp.164. In our specific case, there
are only two alleles, so m=2. \hat{h}_s at the genome level for
each population is simply the mean of the locus estimates for each
population.
Value
a vector of mean population observed heterozygosities (if
by_locus=FALSE), or a matrix of estimates by locus (rows are loci,
columns are populations, by_locus=TRUE)
References
Nei M. (1987) Molecular Evolutionary Genetics. Columbia University Press
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Compute expected heterozygosity
example_gt %>% pop_het_exp()
# To include the global expected heterozygosity, set include_global = TRUE
example_gt %>% pop_het_exp(include_global = TRUE)
# To return by locus, set by_locus = TRUE
example_gt %>% pop_het_exp(by_locus = TRUE)
Compute the population observed heterozygosity
Description
This function computes population heterozygosity, using the formula of Nei (1987).
Usage
pop_het_obs(
.x,
by_locus = FALSE,
include_global = FALSE,
n_cores = bigstatsr::nb_cores()
)
Arguments
.x |
a |
by_locus |
boolean, determining whether Ho should be returned by locus(TRUE), or as a single genome wide value (FALSE, the default). |
include_global |
boolean determining whether, besides the population
specific estimates, a global estimate should be appended. Note that this
will return a vector of n populations plus 1 (the global value), or a
matrix with n+1 columns if |
n_cores |
number of cores to be used, it defaults to
|
Details
Within population observed heterozygosity \hat{h}_o for a
locus with m alleles is defined as:
\hat{h}_o=
1-\sum_{k=1}^{s} \sum_{i=1}^{m} \hat{X}_{kii}/s
where
\hat{X}_{kii} represents the proportion of homozygote i in the
sample for the kth population and
s the number of
populations,
following equation 7.38 in Nei(1987) on pp.164. In our
specific case, there are only two alleles, so m=2. For population
specific estimates, the sum is done over a single value of k.
\hat{h}_o at the genome level is simply the mean of the locus
estimates.
This statistic is ploidy-agnostic: an individual is heterozygous at a
locus whenever its dosage is neither zero nor its own ploidy, so
pop_het_obs() works for diploid, polyploid, and populations that mix
individuals of different ploidy. The genome-wide estimate when
include_global = TRUE is the unweighted mean of the population
estimates for polyploid/mixed-ploidy data; for diploid and pseudohaploid
data it is computed via pop_global_stats(), for consistency with
previous releases.
Value
a vector of mean population observed heterozygosities (if
by_locus=FALSE), or a matrix of estimates by locus (rows are loci,
columns are populations, by_locus=TRUE)
References
Nei M. (1987) Molecular Evolutionary Genetics. Columbia University Press
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Compute expected heterozygosity
example_gt %>% pop_het_obs()
# To include the global expected heterozygosity, set include_global = TRUE
example_gt %>% pop_het_obs(include_global = TRUE)
# To return by locus, set by_locus = TRUE
example_gt %>% pop_het_obs(by_locus = TRUE)
Compute the site frequency spectrum of each population
Description
Compute the one-dimensional site frequency spectrum (SFS) of each
population, i.e. the number of loci with 0, 1, 2, ... copies of the
derived (or minor) allele. Missing genotypes are dealt with as in
easySFS (which relies on dadi), so that the spectra can be used for
demographic inference with dadi, moments or fastsimcoal2. See
pairwise_pop_sfs() for the joint spectra of pairs of populations, and
nwise_pop_sfs() for the joint spectrum of all populations.
Usage
pop_sfs(.x, ...)
## S3 method for class 'tbl_df'
pop_sfs(
.x,
n_proj = NULL,
folded = TRUE,
ancestral = NULL,
type = c("tidy", "array"),
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
pop_sfs(
.x,
n_proj = NULL,
folded = TRUE,
ancestral = NULL,
type = c("tidy", "array"),
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(length(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
pop_sfs(
.x,
n_proj = NULL,
folded = TRUE,
ancestral = NULL,
type = c("tidy", "array"),
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
Arguments
.x |
a |
... |
other arguments passed to specific methods, currently unused. |
n_proj |
the number of allele copies to project each population to:
either a single value used for all populations, a vector with one value
per population (in the order of the groups), or a vector named with the
group labels. If |
folded |
boolean, whether to fold the spectrum (the default, as the
ancestral allele is not usually known). If |
ancestral |
the ancestral allele of each locus, used to polarise
unfolded spectra: either the name of a column of the loci table (see
|
type |
the type of object to return, either "tidy" (the default) or "array". |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
Details
Missing data. Because of missing genotypes, the number of allele
copies called at a locus varies from locus to locus. Each population is
therefore projected down to a fixed number of allele copies, n_proj
(Marth et al. 2004; Gutenkunst et al. 2009): a locus with n called
allele copies, k of which are derived, contributes to cell
j of the spectrum the hypergeometric probability of drawing j
derived copies when sampling n_proj of its n copies without
replacement. Loci with fewer than n_proj called copies are dropped. Each
locus is thus spread over several cells, and the spectrum contains
fractional numbers of sites. This is the approach of easySFS (with the
-a option, i.e. using all loci).
Choosing the projection. Projecting to more allele copies gives more
resolution (more segregating sites, especially rare variants), but drops
more loci with missing data. Following the advice of the dadi manual and
easySFS, use pop_sfs_preview() to compute the number of segregating
sites for each possible projection, and choose a value that keeps most
segregating sites. If n_proj is not given, each population is projected
to the number of allele copies that maximises its number of segregating
sites (the best projection in pop_sfs_preview()).
Folding and polarisation. Unless folded = FALSE, the spectrum is
folded (i.e. it counts copies of the minor allele), as the ancestral allele
is not usually known. An unfolded spectrum counts copies of the derived
allele. By default (ancestral = NULL), the reference allele is taken to
be ancestral, as in easySFS, so that the spectrum counts copies of the
alternate allele: this is only meaningful if the alleles of the
gen_tibble are polarised (note that some operations, such as merging
datasets with rbind(), can swap the reference and alternate alleles).
Otherwise, ancestral gives the ancestral allele of each locus (e.g.
from an outgroup, or the AA field of a vcf), either as a column of the
loci table or as a vector: loci whose ancestral allele is the alternate
allele are polarised (copies of the reference allele are counted), and
loci whose ancestral allele is missing (NA) or is neither of their two
alleles are dropped, as in dadi. Alleles are compared ignoring case.
Polarisation does not change a folded spectrum, so ancestral is ignored
(with a warning) when folded = TRUE.
Masked cells. As in dadi, the corners of the spectrum (sites
monomorphic in the projected sample) are masked, and so are the cells that
were folded out in a folded spectrum. They are reported in the masked
column (or the mask attribute), but keep their values.
Each spectrum only uses the loci that have enough called allele copies in
its own populations. Diploid, polyploid, mixed-ploidy and pseudohaploid
data are supported: each individual contributes as many allele copies as
its ploidy (one for pseudohaploids). The spectrum is computed from the
genotypes currently in use: if the gen_tibble uses imputed genotypes (see
gt_set_imputed()), these are treated as called genotypes, so you will
usually want to use gt_set_imputed(x, FALSE) first.
Note that easySFS samples a single SNP per CHROM (i.e. per RAD locus)
by default; to do the same, thin the loci (e.g. with select_loci())
before computing the spectra.
Value
If type = "tidy", a tibble with one row per cell of the
spectrum of each population, with the columns:
-
group(or one column per grouping variable, if the data are grouped by more than one variable), absent for ungrouped data; -
allele_count: the number of copies of the derived allele (for an unfolded spectrum: the alternate allele, unless the loci are polarised withancestral) or of the minor allele (for a folded spectrum); -
n_sites: the (projected) number of sites; -
masked: whether the cell is masked (see details).
The projection of each population is stored in the attribute n_proj.
The tibble has class pop_sfs_tbl, and can be plotted with
autoplot().
If type = "array", a list of sfs objects (one per population, named
by the group labels), or a single sfs object for ungrouped data. An
sfs object is an array of the numbers of sites, with attributes
giving its mask, the population labels (pop_ids), n_proj, whether
it is folded, and the number of loci used (n_loci), dropped for
lack of called allele copies (n_loci_dropped), and dropped because
their ancestral allele is unknown (n_loci_unpolarised, only with
ancestral). Use tidy() to turn it into a tibble.
References
Marth GT, Czabarka E, Murvai J, Sherry ST (2004) The allele frequency spectrum in genome-wide human variation data reveals signals of differential demographic history in three large world populations. Genetics 166: 351-372.
Gutenkunst RN, Hernandez RD, Williamson SH, Bustamante CD (2009) Inferring the joint demographic history of multiple populations from multidimensional SNP frequency data. PLoS Genetics 5: e1000695.
Overcast I. easySFS. https://github.com/isaacovercast/easySFS
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Preview the number of segregating sites for each projection
example_gt %>% pop_sfs_preview()
# Compute the folded spectra, projecting each population to 2 copies
example_gt %>% pop_sfs(n_proj = 2)
# Project each population to a different number of copies
example_gt %>% pop_sfs(n_proj = c(pop1 = 4, pop2 = 2, pop3 = 2))
# Unfolded spectra, as arrays
example_gt %>% pop_sfs(n_proj = 2, folded = FALSE, type = "array")
# Unfolded spectra, polarised with the ancestral allele of each locus (the
# locus with an unknown ancestral allele is dropped)
show_loci(example_gt)
example_gt %>%
pop_sfs(
n_proj = 2, folded = FALSE,
ancestral = c("T", "C", "C", "G", NA, "T")
)
Preview the projections of the site frequency spectrum
Description
For each population, compute the number of segregating sites in its
site frequency spectrum projected to each possible number of allele
copies (from 2 to the number of allele copies of the population), as the
--preview option of easySFS. This is used to choose n_proj in
pop_sfs(), pairwise_pop_sfs() and nwise_pop_sfs(): projecting to more
allele copies gives more resolution (more segregating sites, especially
rare variants), but drops more loci with missing data. The dadi manual
recommends maximising the number of segregating sites, while keeping a
reasonable sample size.
Usage
pop_sfs_preview(.x, ...)
## S3 method for class 'tbl_df'
pop_sfs_preview(
.x,
ancestral = NULL,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
pop_sfs_preview(
.x,
ancestral = NULL,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(length(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
pop_sfs_preview(
.x,
ancestral = NULL,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
Arguments
.x |
a |
... |
other arguments passed to specific methods, currently unused. |
ancestral |
the ancestral allele of each locus (see |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
Details
The number of segregating sites for a projection to p copies is
the expected number of loci that are polymorphic in a sample of p
copies drawn without replacement from the called copies of each locus
(loci with fewer than p called copies are dropped), i.e. the sum of
the cells of the projected spectrum that are not corners. It is the same
for the folded and unfolded spectrum. If unfolded spectra are polarised
with ancestral (see pop_sfs()), give the same ancestral here, so that
the loci without a known ancestral allele are left out of the preview, as
they are of the spectra.
Value
a tibble with columns group (or one column per grouping
variable, if the data are grouped by more than one variable; absent for
ungrouped data), n_proj (the number of allele copies of the
projection), n_seg_sites (the number of segregating sites, not rounded)
and n_loci (the number of loci with at least n_proj called allele
copies), and best, which is TRUE for the projection that maximises
the number of segregating sites (the largest one in case of ties), used
by default by pop_sfs(), pairwise_pop_sfs() and nwise_pop_sfs().
The tibble has class sfs_preview_tbl, and can be plotted with
autoplot().
See Also
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
example_gt %>% pop_sfs_preview()
# the projection chosen for each population
example_gt %>%
pop_sfs_preview() %>%
dplyr::filter(best)
# plot the number of segregating sites for each projection
example_gt %>%
pop_sfs_preview() %>%
autoplot()
Estimate Tajima's D for the whole genome
Description
Note that Tajima's D estimates from data that have been filtered or ascertained can be difficult to interpret. This function should ideally be used on sequence data prior to filtering.
Usage
pop_tajimas_d(.x, ...)
## S3 method for class 'tbl_df'
pop_tajimas_d(
.x,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
## S3 method for class 'vctrs_bigSNP'
pop_tajimas_d(
.x,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(length(.x), 1),
...
)
## S3 method for class 'grouped_gen_tbl'
pop_tajimas_d(
.x,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(.x), 1),
...
)
Arguments
.x |
a vector of class |
... |
other arguments passed to specific methods, currently unused. |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
Details
Nucleotide diversity is estimated at each locus with loci_pi(), so this
function works with diploid, polyploid, mixed-ploidy and pseudohaploid data.
Missing genotypes are accounted for following Bailey et al. (2025), as
implemented in pixy: the sample size n_x at each locus x is
the number of non-missing allele copies at that locus (i.e. the sum of the
ploidy of the genotyped individuals, with pseudohaploids contributing one
copy each). The two estimators of \theta are then:
-
\hat{\theta}_\pi = \sum_x \pi_x, where\pi_xis the nucleotide diversity at locusx, estimated from itsn_xallele copies (loci with fewer than 2 allele copies contribute 0); -
\hat{\theta}_W = \sum_x 1 / a_{n_x}, summed over the segregating sites, wherea_{n_x} = \sum_{i=1}^{n_x - 1} 1/i(i.e. each segregating site is weighted by its own sample size).
The standard deviation of \hat{\theta}_\pi - \hat{\theta}_W is
computed with the formula of Tajima (1989), using the number of
segregating sites S and the mean sample size across loci with at
least one non-missing allele copy (rounded to the nearest integer, as the
formula is only defined for integer sample sizes). When there are no
missing data, all loci have the same sample size and the statistic is
identical to the classic Tajima's D. Loci with no genotyped individuals
are ignored. Tajima's D is NA when there are no segregating sites, or
when the mean sample size is smaller than 2.
Value
A single numeric value (Tajima's D D) for the whole data set, NA
when the statistic is not defined. For grouped data a list of Tajima's D D
values (one per group) is returned.
References
Tajima F (1989) Statistical method for testing the neutral mutation hypothesis by DNA polymorphism. Genetics 123:585-595.
Bailey N, Stevison L, Samuk K (2025) Correcting for bias in estimates of
\theta_W and Tajima's D from missing data in next-generation
sequencing. Molecular Ecology Resources, e14104.
doi:10.1111/1755-0998.14104
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Compute Tajima's D
example_gt %>% pop_tajimas_d()
Predict scores of a PCA
Description
Predict the PCA scores for a gt_pca, either for the original data or
projecting new data.
Usage
## S3 method for class 'gt_pca'
predict(
object,
new_data = NULL,
project_method = c("least_squares", "simple", "plink", "OADP", "none"),
lsq_pcs = NULL,
block_size = NULL,
n_cores = 1,
as_matrix = TRUE,
...
)
Arguments
object |
the |
new_data |
a gen_tibble if scores are requested for a new dataset |
project_method |
the projection method: |
lsq_pcs |
a vector of the indices of the principal components to use
for the least squares fitting (and to return). Only relevant if
|
block_size |
number of loci read simultaneously (larger values will speed up computation, but require more memory); by default, blocks of about 128 MB. |
n_cores |
number of cores |
as_matrix |
logical, whether to return the result as a matrix (default) or a tibble. |
... |
no used |
Details
New individuals are projected on the loadings of the PCA, with their genotypes centred and scaled as those of the PCA. The methods differ in how they deal with missing genotypes:
-
"least_squares"(the default): for each individual, the least squares fit of its standardised genotypes on the loadings of the loci genotyped in that individual (aslsqprojectin smartpca). Individuals with many missing genotypes are not shrunk towards the centre of the PCA. With complete genotypes, it gives the same scores as"simple". Individuals with too few genotyped loci to fit the components getNA, with a warning. As with"simple"and"OADP", imputed genotypes are used only if thegen_tibbleis set to use them (seegt_set_imputed()). -
"simple": the product of the standardised genotypes, with missing genotypes set to 0 (the mean), by the loadings. An individual with a proportion f of missing genotypes is shrunk towards 0 by a factor of about 1 - f (e.g. to a fifth of its distance with 80% missing genotypes), so it should only be used with complete or imputed data. -
"plink": the simple projection divided by the proportion of loci genotyped in each individual, which is how PLINK 1.9 projects the individuals outside the clusters of--pca-cluster-names(or--pca-clusters). It removes most of the shrinkage of"simple". PLINK standardises the genotypes with the allele frequencies of all the individuals in its run, reference and projected, whereaspredict()uses those of the PCA (seegt_pca()to choose them): the scores are the same as PLINK's when the PCA uses the same frequencies, and PLINK's.eigenvecvalues are these scores divided by the singular values (object$d). Individuals with no genotyped locus getNA. -
"OADP": the Online Augmentation, Decomposition, and Procrustes projection (Zhang et al. 2020), which corrects the shrinkage of projections with many more loci than individuals; missing genotypes are set to 0, as for"simple", with the same shrinkage. -
"none": the product of the genotypes by the loadings withbigstatsr::big_prodMat(); it needs complete or imputed genotypes (and uses imputed genotypes automatically).
In a simulation of individuals with 20-80% missing genotypes projected on
complete reference individuals, "least_squares" had no shrinkage and the
smallest error, "simple" and "OADP" shrank individuals by their
proportion of missing genotypes, and imputing the genotypes (by their mode)
before a simple projection only halved the shrinkage. "plink" was close
to "least_squares" with the frequencies of the reference individuals, and
had a larger error with those of all the individuals, as PLINK does.
Value
a matrix of predictions (in line with predict using a prcomp
object) or a tibble, with samples as rows and components as columns. The
number of components depends on how many were estimated in the gt_pca
object.
References
Zhang et al (2020). Fast and robust ancestry prediction using principal component analysis. Bioinformatics 36(11): 3439–3446.
Patterson N., Price A.L. and Reich D. (2006) Population structure and eigenanalysis. PLoS Genetics 2: e190.
Privé F., Luu K., Blum M.G.B., McGrath J.J. and Vilhjálmsson B.J. (2020)
Efficient toolkit implementing best practices for principal component
analysis of population genetic data. Bioinformatics 36: 4449-4457 (for
the implementation of OADP in bigsnpr, which "OADP" uses).
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci and impute
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
lobsters <- gt_impute_simple(lobsters, method = "mode")
# Subset into two datasets: one original and one to predict
original_lobsters <- lobsters[c(1:150), ]
new_lobsters <- lobsters[c(151:176), ]
# Create PCA object
pca <- gt_pca(original_lobsters)
# Predict
predict(pca, new_data = new_lobsters, project_method = "simple")
# Predict as PLINK 1.9
predict(pca, new_data = new_lobsters, project_method = "plink")
# Predict with OADP
predict(pca, new_data = new_lobsters, project_method = "OADP")
# Predict with least squares (the default), on the first three components
predict(pca, new_data = new_lobsters, lsq_pcs = c(1, 2, 3))
# Return a tibble
predict(pca, new_data = new_lobsters, as_matrix = FALSE)
# Adjust block.size
predict(pca, new_data = new_lobsters, block_size = 10)
Print method for matrix_int_names
Description
Print method for matrix_int_names
Usage
## S3 method for class 'matrix_int_names'
print(x, ..., n = 10L)
Arguments
x |
A matrix_int_names object |
... |
Additional arguments passed to print |
n |
Optional number of rows/columns to print (default 10) |
Value
Invisibly returns the original object
See Also
Other matrix_int_names_functions:
[.matrix_int_names(),
as.data.frame.matrix_int_names(),
col_names(),
matrix_int_names(),
row_names()
Examples
my_mat <- matrix_int_names(matrix(1:6, nrow = 2),
row_names = c(10L, 20L),
col_names = c(100L, 200L, 300L)
)
print(my_mat)
print(my_mat, n = 2)
Convert a standard matrix to a q_matrix object
Description
Takes a single Q matrix that exists as either a matrix or a data frame and
returns a q_matrix object.
Usage
q_matrix(x)
Arguments
x |
A matrix or a data frame |
Value
A q_matrix object
Examples
# Read in a single .Q file
q_mat <- read.table(system.file("extdata", "anolis", "anolis_ld_run1.3.Q",
package = "tidypopgen"
))
class(q_mat)
# Convert to a Q matrix object
q_mat <- q_matrix(q_mat)
class(q_mat)
Create a Quality Control report for individuals
Description
Return QC information to assess individuals (Observed heterozygosity and missingness).
Usage
qc_report_indiv(.x, ...)
## S3 method for class 'gen_tbl'
qc_report_indiv(.x, kings_threshold = NULL, ...)
## S3 method for class 'grouped_gen_tbl'
qc_report_indiv(.x, kings_threshold = NULL, ...)
Arguments
.x |
either a |
... |
further arguments to pass |
kings_threshold |
an optional numeric giving a KING kinship coefficient, or one of:
|
Details
Providing the parameter kings_threshold will return two additional columns, 'id' containing the ID of individuals, and 'to_keep' a logical vector describing whether the individual should be removed to retain the largest possible set of individuals with no relationships above the threshold. The calculated pairwise KING relationship matrix is also returned as an attribute of 'to_keep'. The kings_threshold parameter can be either a numeric KING kinship coefficient or a string of either "first" or "second", to remove any first degree or second degree relationships from the dataset. This second option is similar to using –unrelated –degree 1 or –unrelated –degree 2 in KING. For pseudohaploid data, only missingness and ploidy are reported.
Value
If no kings_threshold is provided, a tibble with 2 elements: het_obs and missingness. If kings_threshold is provided, a tibble with 4 elements: het_obs, missingness, id and to_keep. For pseudohaploid data, a tibble with ploidy and missingness.
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
example_gt <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Get QC report for individuals
example_gt %>% qc_report_indiv()
# Get QC report with kinship filtering
example_gt %>% qc_report_indiv(kings_threshold = "first")
Create a Quality Control report for loci
Description
Return QC information to assess loci (MAF, missingness and HWE test). For pseudohaploid data, HWE test is not calculated.
Usage
qc_report_loci(.x, hwe = TRUE, n_cores = bigstatsr::nb_cores(), ...)
## S3 method for class 'gen_tbl'
qc_report_loci(.x, hwe = TRUE, n_cores = bigstatsr::nb_cores(), ...)
## S3 method for class 'grouped_gen_tbl'
qc_report_loci(.x, hwe = TRUE, n_cores = bigstatsr::nb_cores(), ...)
Arguments
.x |
a |
hwe |
boolean, whether to compute the HWE exact test (the default). It is never computed for pseudohaploid data. |
n_cores |
number of cores to be used, it defaults to
|
... |
currently unused |
Details
The MAF and the missingness are always computed across all individuals:
grouping only affects the HWE test, which is computed within each group.
When genotypes are coded as 0, 1, 2 or missing (raw or imputed calls), all
statistics are computed in a single pass over the genotypes. With
hwe = FALSE, qc_report_loci() thus gives both the MAF and the
missingness of each locus, identical to loci_maf() and
loci_missingness() on the ungrouped data, reading the genotypes once
rather than twice (e.g. to filter loci on both with select_loci_if()).
Value
either a tibble with 3 elements (maf, missingness and hwe_p). For
pseudohaploid data, or if hwe = FALSE, a tibble with 2 elements (maf
and missingness).
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
example_gt <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Get a QC report for the loci
example_gt %>% qc_report_loci()
# Only MAF and missingness (in a single pass over the genotypes), e.g. to
# filter loci on both
loci_qc <- example_gt %>% qc_report_loci(hwe = FALSE)
example_gt %>%
select_loci_if(loci_qc$maf >= 0.05 & loci_qc$missingness <= 0.2)
# Group by population to calculate HWE within populations
example_gt <- example_gt %>% group_by(population)
example_gt %>% qc_report_loci()
Combine two gen_tibbles
Description
This function combined two gen_tibbles. It subsets the loci and swaps ref and alt alleles to make the two datasets compatible. The first object is used as a "reference" , and SNPs in the other dataset will be flipped and/or alleles swapped as needed. SNPs that have different alleles in the two datasets (i.e. triallelic) will also be dropped. There are also options (NOT default) to attempt strand flipping to match alleles (often needed in human datasets from different SNP chips), and remove ambiguous alleles (C/G and A/T) where the correct strand can not be guessed.
Usage
## S3 method for class 'gen_tbl'
rbind(
...,
as_is = FALSE,
flip_strand = FALSE,
use_position = FALSE,
quiet = FALSE,
backingfile = NULL
)
Arguments
... |
two |
as_is |
deprecated, and ignored: |
flip_strand |
boolean on whether strand flipping should be checked to
match the two datasets. If this is set to TRUE, ambiguous SNPs (i.e. A/T
and C/G) will also be removed, and loci whose |
use_position |
boolean of whether a combination of chromosome and
position should be used for matching SNPs. By default, |
quiet |
boolean whether to omit reporting to screen |
backingfile |
the path and prefix of the files used to store the merged
data (it will be a .RDS to store the |
Details
Loci are matched by name, unless use_position = TRUE. If the loci names of
either gen_tibble are integers (as created by gen_tibble(names_as_int = TRUE)), loci are always matched by chromosome and position (see
use_position).
rbind differs from merging data with plink, which swaps the order of allele1 and allele2 according to minor allele frequency when merging datasets. rbind flips and/or swaps alleles according to the reference dataset, not according to allele frequency.
If both gen_tibbles are phased (see phased in gen_tibble()), the merged
gen_tibble is phased too, and the alleles of phased genotypes are never
swapped or flipped: rbind stops with an error if flip_strand = TRUE, or
if the reference and alternate alleles of any locus in common are swapped
between the two datasets (use rbind_dry_run() to find these loci, in the
column to_swap of its target table, and select_loci() to remove
them). If only one of them is phased, the phase of its genotypes is
discarded (with a message), and the two datasets are merged as unphased
data (swapping alleles as needed).
If the first gen_tibble is grouped, the merged gen_tibble is grouped by
the same variables (as with dplyr::bind_rows()); the grouping of the
second gen_tibble is ignored.
Value
a gen_tibble with the merged data.
Examples
example_gt <- load_example_gt("gen_tbl")
# Create a second gen_tibble to merge
test_indiv_meta <- data.frame(
id = c("x", "y", "z"),
population = c("pop1", "pop1", "pop2")
)
test_genotypes <- rbind(
c(1, 1, 0, 1, 1, 0),
c(2, 1, 0, 0, 0, 0),
c(2, 2, 0, 0, 1, 1)
)
test_loci <- data.frame(
name = paste0("rs", 1:6),
chromosome = paste0("chr", c(1, 1, 1, 1, 2, 2)),
position = as.integer(c(3, 5, 65, 343, 23, 456)),
genetic_dist = as.double(rep(0, 6)),
allele_ref = c("A", "T", "C", "G", "C", "T"),
allele_alt = c("T", "C", NA, "C", "G", "A")
)
test_gt <- gen_tibble(
x = test_genotypes,
loci = test_loci,
indiv_meta = test_indiv_meta,
valid_alleles = c("A", "T", "C", "G"),
quiet = TRUE
)
# Merge the datasets using rbind
merged_gt <- rbind(ref = example_gt, target = test_gt, flip_strand = TRUE)
merged_gt
Generate a report of what would happen to each SNP in a merge
Description
This function provides an overview of the fate of each SNP in two
gen_tibble objects in the case of a merge. Only SNPs found in both
objects will be kept. One object is used as a reference, and SNPs in the
other dataset will be flipped and/or alleles swapped as needed. SNPs that
have different alleles in the two datasets will also be dropped.
Usage
rbind_dry_run(
ref,
target,
use_position = FALSE,
flip_strand = FALSE,
quiet = FALSE
)
Arguments
ref |
either a |
target |
either a |
use_position |
boolean of whether a combination of chromosome and
position should be used for matching SNPs. By default, |
flip_strand |
boolean on whether strand flipping should be checked to match the two datasets. Ambiguous SNPs (i.e. A/T and C/G) will also be removed. It defaults to FALSE |
quiet |
boolean whether to omit reporting to screen |
Details
Loci are matched by name, unless use_position = TRUE. If the loci names of
either dataset are integers (as created by gen_tibble(names_as_int = TRUE)), loci are always matched by chromosome and position (see
use_position).
Value
a list with two data.frames, named target and ref. Each
data.frame has nrow() equal to the number of loci in the respective
dataset, and columns id (the index of the locus in the dataset), new_id
(the index of the locus in the merged dataset, NA if the locus is dropped,
either because it is not found in both datasets, because its alleles do not
match, or because it is ambiguous), name (the locus name, also when loci
are matched by position), to_flip
(boolean, loci whose strand is flipped to match the reference, only in the
target data.frame), to_swap (boolean, loci whose alleles, and thus
genotypes, are swapped in the merge: in target, to match the order of
alleles in the reference; in ref, loci whose allele_ref is missing in
both datasets, which are swapped so that the observed allele becomes
allele_ref, only when flip_strand = TRUE), missing_allele and
missing_allele_col (for loci with one unobserved allele (NA), the allele
inferred from the other dataset, and the column it fills, allele_alt or
allele_ref; both are NA if nothing was inferred), and ambiguous
(boolean, strand-ambiguous loci, i.e. A/T and C/G).
Examples
example_gt <- load_example_gt("gen_tbl")
# Create a second gen_tibble to merge
test_indiv_meta <- data.frame(
id = c("x", "y", "z"),
population = c("pop1", "pop1", "pop2")
)
test_genotypes <- rbind(
c(1, 1, 2, 1, 1),
c(2, 1, 2, 0, 0),
c(2, 2, 2, 0, 1)
)
test_loci <- data.frame(
name = paste0("rs", 1:5),
chromosome = paste0("chr", c(1, 1, 1, 1, 2)),
position = as.integer(c(3, 5, 65, 343, 23)),
genetic_dist = as.double(rep(0, 5)),
allele_ref = c("A", "T", "C", "G", "C"),
allele_alt = c("T", "C", NA, "C", "G")
)
test_gt <- gen_tibble(
x = test_genotypes,
loci = test_loci,
indiv_meta = test_indiv_meta,
valid_alleles = c("A", "T", "C", "G"),
quiet = TRUE
)
# Create an rbind report using rbind_dry_run
rbind_dry_run(example_gt, test_gt, flip_strand = TRUE)
Read and structure .Q files or existing matrices as q_matrix or gt_admix
objects.
Description
This function reads .Q matrix files generated by external clustering
algorithms (such as ADMIXTURE) and transforms them into gt_admix objects.
Usage
read_q_files(x)
Arguments
x |
can be:
|
Value
a
gt_admixobject containing a list of Q matrices and a list of indices for each Q matrix separated by K
Examples
q_files_path <- system.file("extdata", "anolis", package = "tidypopgen")
admix_obj <- read_q_files(q_files_path)
summary(admix_obj)
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
- generics
- ggplot2
Get or set row names for matrix_int_names
Description
Returns integer names if present, otherwise character dimnames. Use instead
of rownames() for guaranteed dispatch.
Usage
row_names(x)
row_names(x) <- value
## Default S3 replacement method:
row_names(x) <- value
## S3 replacement method for class 'matrix_int_names'
row_names(x) <- value
Arguments
x |
A matrix_int_names object |
value |
Integer or character vector of row names, or NULL |
Value
Integer or character vector of row names, or NULL
The modified matrix_int_names object
See Also
Other matrix_int_names_functions:
[.matrix_int_names(),
as.data.frame.matrix_int_names(),
col_names(),
matrix_int_names(),
print.matrix_int_names()
Examples
my_mat <- matrix_int_names(matrix(1:6, nrow = 2),
row_names = c(10L, 20L),
col_names = c(100L, 200L, 300L)
)
row_names(my_mat)
row_names(my_mat) <- c(1L, 2L)
row_names(my_mat)
Scale constructor using the distruct colours
Description
A discrete fill scale using the distruct colours from
distruct_colours, in order. With more groups than colours (56), the
colours are recycled, with a warning, so some groups share a colour.
Usage
scale_fill_distruct(guide = "none", ...)
Arguments
guide |
guide function passed to |
... |
further parameters to be passed to |
Value
a scale constructor to be used with ggplot
See Also
ggplot2::scale_fill_manual(), which this function used to wrap
(it can not recycle colours).
Examples
library(ggplot2)
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Fill bars of individuals per population with the distruct colours
ggplot(lobsters, aes(x = population, fill = population)) +
geom_bar() +
scale_fill_distruct()
The select verb for loci
Description
An equivalent to dplyr::select() that works on the genotype column
of a gen_tibble, using the mini-grammar available for tidyselect. The
select-like evaluation only has access to the names of the loci (i.e. it
can select only based on names, not summary statistics of those loci; look
at select_loci_if() for that feature.
Usage
select_loci(.data, .sel_arg, .engine = c("auto", "tidyselect"))
Arguments
.data |
a |
.sel_arg |
one unquoted expression, using the mini-grammar of
|
.engine |
how the selection is resolved: "auto" (the default)
resolves the common selections described in Details directly, and leaves
the others to |
Details
Note that the select_loci verb does not modify the backing FBM files,
but rather it subsets the list of loci to be used stored in the gen_tibble.
For large datasets (millions of loci), select loci with dplyr::all_of()
or dplyr::any_of(), with helpers that match names (such as
dplyr::starts_with() or dplyr::everything()), with numeric positions
written as numbers (e.g. 1:100 or -c(1, 5)), with a function call
that gives positions or names (e.g. which(...), sample(...) or
sort(x)), or with a variable that holds positions or names (e.g.
select_loci(x, idx)), each optionally negated with - or !. These
selections are resolved directly, which is much faster and uses much less
memory than the general tidyselect machinery, which has to create an R
symbol for every locus name (and R never frees symbols). As in
tidyselect, a locus with the same name as the variable is selected
instead of the value of the variable, and selecting with a variable gives
the deprecation warning of tidyselect: prefer all_of(idx), which can
not be confused with a locus named idx. Other expressions (e.g.
combinations such as c(all_of(x), starts_with("rs")), or bare loci
names) still work, but are slow and memory hungry on very large datasets.
To always use tidyselect (e.g. if a selection is not resolved as
tidyselect would resolve it), set .engine = "tidyselect".
Value
a gen_tibble with a subset of the loci.
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
# Select loci by name
example_gt_subset <- example_gt %>%
select_loci(all_of(c("rs1", "rs2", "rs3")))
show_loci(example_gt_subset)
# Select loci by index
example_gt_subset <- example_gt %>% select_loci(all_of(c(4, 2, 1)))
show_loci(example_gt_subset)
# Always use tidyselect to resolve the selection
example_gt_subset <- example_gt %>%
select_loci(all_of(c(4, 2, 1)), .engine = "tidyselect")
The select_if verb for loci
Description
An equivalent to dplyr::select_if() that works on the genotype column
of a gen_tibble. This function has access to the genotypes (and thus can
work on summary statistics to select), but not the names of the loci (look
at select_loci() for that feature.
Usage
select_loci_if(.data, .sel_logical)
Arguments
.data |
a |
.sel_logical |
a logical vector of length equal to the number of loci, or an expression that will tidy evaluate to such a vector. Only loci for which .sel_logical is TRUE will be selected; NA will be treated as FALSE. |
Details
Note that the select_loci_if verb does not modify the backing FBM files,
but rather it subsets the list of loci to be used stored in the gen_tibble.
Groups are ignored: all individuals share the same loci, so a locus is kept
or dropped for all groups at once, and .sel_logical is evaluated once,
on all the individuals of the gen_tibble, even if it is grouped (e.g.
loci_maf(genotypes) is the minor allele frequency over all individuals,
not within each group). This is also how qc_report_loci() computes the
minor allele frequency and missingness of a grouped gen_tibble (only
Hardy-Weinberg equilibrium is tested within groups). To select loci on
statistics computed within each group, compute them on the grouped
gen_tibble (e.g. loci_maf(type = "matrix"), with one column per group),
and combine them into one logical value per locus (see the examples).
Value
a subset of the list of loci in the gen_tibble
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
# Select loci by chromosome
example_gt_subset <- example_gt %>%
select_loci_if(loci_chromosomes(genotypes) == "chr2")
show_loci(example_gt_subset)
# Select loci by a summary statistic
example_gt_subset <- example_gt %>%
select_loci_if(loci_maf(genotypes) > 0.2)
show_loci(example_gt_subset)
# Groups are ignored: this also selects loci with a minor allele frequency
# above 0.2 over all individuals
grouped_gt <- example_gt %>% group_by(population)
grouped_gt_subset <- grouped_gt %>%
select_loci_if(loci_maf(genotypes) > 0.2)
show_loci(grouped_gt_subset)
# To select loci with a minor allele frequency above 0.2 in every
# population, compute it within populations (one column per population)
maf_by_pop <- grouped_gt %>% loci_maf(type = "matrix")
grouped_gt_subset <- grouped_gt %>%
select_loci_if(apply(maf_by_pop, 1, min) > 0.2)
show_loci(grouped_gt_subset)
Show the genotypes of a gen_tibble
Description
Extract the genotypes (as a matrix) from a gen_tibble.
Usage
show_genotypes(.x, indiv_indices = NULL, loci_indices = NULL, ...)
## S3 method for class 'tbl_df'
show_genotypes(.x, indiv_indices = NULL, loci_indices = NULL, ...)
## S3 method for class 'vctrs_bigSNP'
show_genotypes(.x, indiv_indices = NULL, loci_indices = NULL, ...)
Arguments
.x |
a vector of class |
indiv_indices |
indices of individuals |
loci_indices |
indices of loci |
... |
currently unused. |
Value
a matrix of counts of the alternative alleles (see show_loci()) to
extract information on the alleles for those loci from a gen_tibble.
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% show_genotypes()
Show the haplotypes of a phased gen_tibble
Description
Extract the haplotypes (as a matrix) from a phased gen_tibble (read with
phased = TRUE in gen_tibble()).
Usage
show_haplotypes(.x, indiv_indices = NULL, loci_indices = NULL)
Arguments
.x |
a phased |
indiv_indices |
the indices of the individuals (rows of |
loci_indices |
the indices of the loci to show. |
Value
an integer matrix with two rows per individual (its first and
second haplotypes, named <id>_1 and <id>_2) and one column per locus
(named after the locus), with 0 for the reference allele, 1 for the
alternate allele and NA for missing genotypes.
See Also
show_genotypes() for the dosages of the alternate allele.
Examples
vcf_path <- system.file("extdata", "phased_example.vcf",
package = "tidypopgen"
)
x <- gen_tibble(vcf_path,
phased = TRUE,
backingfile = tempfile("phased_"),
quiet = TRUE
)
show_haplotypes(x)
show_haplotypes(x, indiv_indices = 1:2, loci_indices = 2:4)
Show the loci information of a gen_tibble
Description
Extract and set the information on loci from a gen_tibble.
Usage
show_loci(.x, ...)
## S3 method for class 'tbl_df'
show_loci(.x, ...)
## S3 method for class 'vctrs_bigSNP'
show_loci(.x, ...)
show_loci(.x) <- value
## S3 replacement method for class 'tbl_df'
show_loci(.x) <- value
## S3 replacement method for class 'vctrs_bigSNP'
show_loci(.x) <- value
Arguments
.x |
a vector of class |
... |
currently unused. |
value |
a data.frame or tibble of loci information to replace the current one. |
Value
a tibble::tibble of information (see gen_tibble for details
on compulsory columns that will always be present)
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% show_loci()
Show the ploidy information of a gen_tibble
Description
Extract the ploidy information from a gen_tibble. NOTE that this function
does not return the ploidy level for each individual (that is obtained with
indiv_ploidy); instead, it returns an integer which is either the ploidy
level of all individuals (e.g. 2 indicates all individuals are diploid),
or a 0 to indicate mixed ploidy. The special case of -2 is used to indicate
the presence of pseudo-haploids (i.e. individuals with a ploidy of 2 but
for which we only have information for one allele; the dosages are 0 or 2
for these individuals).
Usage
show_ploidy(.x, ...)
## S3 method for class 'tbl_df'
show_ploidy(.x, ...)
## S3 method for class 'vctrs_bigSNP'
show_ploidy(.x, ...)
Arguments
.x |
a vector of class |
... |
currently unused. |
Value
the ploidy (0 indicates mixed ploidy)
See Also
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>% show_ploidy()
Compute the Pairwise Allele Sharing Matrix for a bigSNP object
Description
This function computes the Allele Sharing matrix. Estimates Allele Sharing
(matching in hierfstat)) between pairs of individuals (for each locus,
gives 1 if the two individuals are homozygous for the same allele, 0 if they
are homozygous for a different allele, and 1/2 if at least one individual is
heterozygous. Matching is the average of these 0, 1/2 and 1s)
Usage
snp_allele_sharing(
X,
ind.row = bigstatsr::rows_along(X),
ind.col = bigstatsr::cols_along(X),
block.size = bigstatsr::block_size(nrow(X)),
n_cores = bigstatsr::nb_cores()
)
Arguments
X |
a bigstatsr::FBM.code256 matrix (as found in the |
ind.row |
An optional vector of the row indices that are used. If not specified, all rows are used. Don't use negative indices. |
ind.col |
An optional vector of the column indices that are used. If not specified, all columns are used. Don't use negative indices. |
block.size |
maximum number of columns read at once. Genotypes are compared in a compact bit-packed form, so this has little effect on memory use. |
n_cores |
number of cores to be used, it defaults to
|
Value
a matrix of allele sharing between all pairs of individuals
See Also
pairwise_allele_sharing() hierfstat::matching()
Examples
example_gt <- load_example_gt("gen_tbl")
X <- attr(example_gt$genotypes, "fbm")
snp_allele_sharing(X)
# Compute for individuals 1 to 5
snp_allele_sharing(X, ind.row = 1:5, ind.col = 1:5)
# Adjust block size
snp_allele_sharing(X, block.size = 2)
Compute the Identity by State Matrix for a bigSNP object
Description
This function computes the IBS matrix.
Usage
snp_ibs(
X,
ind.row = bigstatsr::rows_along(X),
ind.col = bigstatsr::cols_along(X),
type = c("proportion", "adjusted_counts", "raw_counts"),
block.size = bigstatsr::block_size(nrow(X)),
n_cores = bigstatsr::nb_cores(),
missing_correction = c("flat", "allele_freq"),
allele_freqs = NULL
)
Arguments
X |
a bigstatsr::FBM.code256 matrix (as found in the |
ind.row |
An optional vector of the row indices that are used. If not specified, all rows are used. Don't use negative indices. |
ind.col |
An optional vector of the column indices that are used. If not specified, all columns are used. Don't use negative indices. |
type |
one of:
|
block.size |
maximum number of columns read at once. Genotypes are compared in a compact bit-packed form, so this has little effect on memory use. |
n_cores |
number of cores to be used, it defaults to
|
missing_correction |
the correction for missing genotypes of
"proportion" and "adjusted_counts": "flat" (the default, as PLINK 1.9's
|
allele_freqs |
only used if |
Details
Note that monomorphic sites are counted (as in PLINK). Remove monomorphic sites beforehand if this is a concern.
See pairwise_ibs() for the two corrections for missing genotypes
(missing_correction).
Value
for "proportion" and "adjusted_counts", a matrix with one row and
one column per individual; for "raw_counts", a list of two
bigstatsr::FBM matrices, ibs (the counts of alleles identical by
state) and valid_n (the counts of non-missing alleles, i.e. twice the
number of loci genotyped in both individuals).
Examples
example_gt <- load_example_gt("gen_tbl")
X <- attr(example_gt$genotypes, "fbm")
snp_ibs(X)
# Compute for individuals 1 to 5
snp_ibs(X, ind.row = 1:5, ind.col = 1:5)
# Adjust block.size
snp_ibs(X, block.size = 2)
# Change type
snp_ibs(X, type = "proportion")
snp_ibs(X, type = "adjusted_counts")
snp_ibs(X, type = "raw_counts")
# PLINK 1.9's default correction for missing genotypes
snp_ibs(X, type = "adjusted_counts", missing_correction = "allele_freq")
Compute the KING-robust Matrix for a bigSNP object
Description
This function computes the KING-robust estimator of kinship, reimplementing the KING algorithm of Manichaikul et al. (2010).
Usage
snp_king(
X,
ind.row = bigstatsr::rows_along(X),
ind.col = bigstatsr::cols_along(X),
block.size = bigstatsr::block_size(nrow(X)) * 4,
n_cores = bigstatsr::nb_cores()
)
Arguments
X |
a bigstatsr::FBM.code256 matrix (as found in the |
ind.row |
An optional vector of the row indices that are used. If not specified, all rows are used. Don't use negative indices. |
ind.col |
An optional vector of the column indices that are used. If not specified, all columns are used. Don't use negative indices. |
block.size |
maximum number of columns read at once. Genotypes are compared in a compact bit-packed form, so this has little effect on memory use. |
n_cores |
number of cores to be used, it defaults to
|
Value
a square symmetrical matrix of relationship coefficients between individuals
References
Manichaikul, A. et al. (2010) Robust relationship inference in genome-wide association studies. Bioinformatics, 26(22), 2867–2873. https://doi.org/10.1093/bioinformatics/btq559.
Examples
example_gt <- load_example_gt("gen_tbl")
X <- attr(example_gt$genotypes, "fbm")
snp_king(X)
# Compute for individuals 1 to 5
snp_king(X, ind.row = 1:5, ind.col = 1:5)
# Adjust block size
snp_king(X, block.size = 2)
Summary method for gt_admix objects
Description
Summary method for gt_admix objects
Usage
## S3 method for class 'gt_admix'
summary(object, ...)
Arguments
object |
a |
... |
unused (necessary for compatibility with generic function) |
Value
A summary of the gt_admix object
Examples
# run the example only if we have the package installed
if (requireNamespace("LEA", quietly = TRUE)) {
example_gt <- load_example_gt("gen_tbl")
# Create a gt_admix object
admix_obj <- example_gt %>% gt_snmf(k = 1:3, project = "force")
# Print a summary
summary(admix_obj)
}
Print a summary of a merge report
Description
This function creates a summary of the merge report generated by
rbind_dry_run()
Usage
## S3 method for class 'rbind_report'
summary(object, ..., ref_label = "reference", target_label = "target")
Arguments
object |
a list generated by |
... |
unused (necessary for compatibility with generic function) |
ref_label |
the label for the reference dataset (defaults to "reference") |
target_label |
the label for the target dataset (defaults to "target") |
Value
NULL (prints a summary to the console)
Examples
example_gt <- load_example_gt("gen_tbl")
# Create a second gen_tibble to merge
test_indiv_meta <- data.frame(
id = c("x", "y", "z"),
population = c("pop1", "pop1", "pop2")
)
test_genotypes <- rbind(
c(1, 1, 0, 1, 1, 0),
c(2, 1, 0, 0, 0, 0),
c(2, 2, 0, 0, 1, 1)
)
test_loci <- data.frame(
name = paste0("rs", 1:6),
chromosome = paste0("chr", c(1, 1, 1, 1, 2, 2)),
position = as.integer(c(3, 5, 65, 343, 23, 456)),
genetic_dist = as.double(rep(0, 6)),
allele_ref = c("A", "T", "C", "G", "C", "T"),
allele_alt = c("T", "C", NA, "C", "G", "A")
)
test_gt <- gen_tibble(
x = test_genotypes,
loci = test_loci,
indiv_meta = test_indiv_meta,
valid_alleles = c("A", "T", "C", "G"),
quiet = TRUE
)
# Merge the datasets using rbind
report <- rbind_dry_run(
ref = example_gt, target = test_gt,
flip_strand = TRUE, quiet = TRUE
)
# Get the summary
summary(report)
A theme to match the output of distruct
Description
A theme to remove most plot decorations, matching the look of plots created with distruct.
Usage
theme_distruct()
Value
Examples
# Read example gt_admix object
admix_obj <-
readRDS(system.file("extdata", "anolis", "anole_adm_k3.rds",
package = "tidypopgen"
))
# Basic barplot with disstruct theme
autoplot(admix_obj, k = 3, run = 1, type = "barplot") +
theme_distruct()
Tidy a gt_dapc object
Description
This summarizes information about the components of a gt_dapc from the
tidypopgen package. The parameter matrix determines which element is
returned.
Usage
## S3 method for class 'gt_dapc'
tidy(x, matrix = "eigenvalues", ...)
Arguments
x |
A |
matrix |
Character specifying which component of the DAPC should be tidied.
|
... |
Not used. Needed to match generic signature only. |
Value
A tibble::tibble with columns depending on the component of DAPC being tidied.
If "scores" each row in the tidied output corresponds to the original
data in PCA space. The columns are:
row |
ID of the original observation (i.e. rowname from original data). |
LD |
Integer indicating a principal component. |
value |
The score of the observation for that particular principal component. That is, the location of the observation in PCA space. |
If matrix is "loadings", each row in the tidied output corresponds to
information about the principle components in the original space. The
columns are:
column |
The variable labels (colnames) of the data set on which PCA was performed. |
LD |
A character vector indicating the discriminant axis (e.g. "LD1"). |
value |
The value of the eigenvector (axis score) on the indicated principal component. |
If "eigenvalues", the columns are:
LD |
An integer vector indicating the discriminant axis. |
std.dev |
Standard deviation (i.e. sqrt(eig/(n-1))) explained by
this DA (for compatibility with |
cumulative |
Cumulative variation explained by principal components up to this component (note that this is NOT phrased as a percentage of total variance, since many methods only estimate a truncated SVD. |
See Also
Examples
#' # Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA and run DAPC (with missing genotypes, the loadings of the
# loci need the genotypes, `data`)
pca <- gt_pca(lobsters)
populations <- as.factor(lobsters$population)
dapc_res <- gt_dapc(pca,
n_pca = 6, n_da = 2, pop = populations, data = lobsters
)
# Tidy scores
tidy(dapc_res, matrix = "scores")
# Tidy eigenvalues
tidy(dapc_res, matrix = "eigenvalues")
# Tidy loadings
tidy(dapc_res, matrix = "loadings")
Tidy a gt_pca object
Description
This summarizes information about the components of a gt_pca from the
tidypopgen package. The parameter matrix determines which element is
returned. Column names of the tidied output match those returned by
broom::tidy.prcomp, the tidier for the standard PCA objects returned
by stats::prcomp.
Usage
## S3 method for class 'gt_pca'
tidy(x, matrix = "eigenvalues", ...)
Arguments
x |
A |
matrix |
Character specifying which component of the PCA should be tidied.
|
... |
Not used. Needed to match generic signature only. |
Value
A tibble::tibble with columns depending on the component of PCA being tidied.
If "scores" each row in the
tidied output corresponds to the original data in PCA space. The columns
are:
row |
ID of the original observation (i.e. rowname from original data). |
PC |
Integer indicating a principal component. |
value |
The score of the observation for that particular principal component. That is, the location of the observation in PCA space. |
If matrix is "loadings", each
row in the tidied output corresponds to information about the principle
components in the original space. The columns are:
row |
The variable labels (colnames) of the data set on which PCA was performed. |
PC |
An integer vector indicating the principal component. |
value |
The value of the eigenvector (axis score) on the indicated principal component. |
If "eigenvalues", the columns are:
PC |
An integer vector indicating the principal component. |
std.dev |
Standard deviation (i.e. sqrt(eig/(n-1))) explained by
this PC (for compatibility with |
cumulative |
Cumulative variation explained by principal components up to this component (note that this is NOT phrased as a percentage of total variance, since many methods only estimate a truncated SVD. |
See Also
gt_pca() gt_pca_autoSVD() augment_gt_pca
Examples
# Create a gen_tibble of lobster genotypes
bed_file <-
system.file("extdata", "lobster", "lobster.bed", package = "tidypopgen")
lobsters <- gen_tibble(bed_file,
backingfile = tempfile("lobsters"),
quiet = TRUE
)
# Remove monomorphic loci
lobsters <- lobsters %>% select_loci_if(loci_maf(genotypes) > 0)
# Create PCA object
pca <- gt_pca(lobsters)
# Tidy the PCA object
tidy(pca)
# Tidy the PCA object for eigenvalues
tidy(pca, matrix = "eigenvalues")
# Tidy the PCA object for loadings
tidy(pca, matrix = "loadings")
# Tidy the PCA object for scores
tidy(pca, matrix = "scores")
Tidy a Q matrix
Description
Takes a q_matrix object, which is a matrix, and returns a tidied tibble.
Usage
## S3 method for class 'q_matrix'
tidy(x, data, ...)
Arguments
x |
A Q matrix object (as returned by |
data |
An associated tibble (e.g. a |
... |
not currently used |
Value
A tidied tibble containing columns:
row |
ID of the original observation (i.e. rowname from original data). |
Q |
Integer indicating a Q component. |
value |
The proportion for that particular Q value. |
Examples
# run the example only if we have the package installed
if (requireNamespace("LEA", quietly = TRUE)) {
example_gt <- load_example_gt("gen_tbl")
# Create a gt_admix object
admix_obj <- example_gt %>% gt_snmf(k = 1:3, project = "force")
# Extract a Q matrix
q_mat_k3 <- get_q_matrix(admix_obj, k = 3, run = 1)
tidy(q_mat_k3, data = example_gt)
}
Tidy a site frequency spectrum
Description
Turn an sfs object (as returned by pop_sfs(), pairwise_pop_sfs() and
nwise_pop_sfs() with type = "array") into a tibble with one row per
cell of the spectrum.
Usage
## S3 method for class 'sfs'
tidy(x, fastest = c("last", "first"), ...)
Arguments
x |
an |
fastest |
which population's number of allele copies changes fastest from one row to the next: "last" (the default, which keeps the order of the populations: rows are sorted by the number of copies in the first population, then in the second, and so on, as in the files written by dadi and easySFS) or "first". |
... |
currently unused. |
Value
a tibble with one column per population (named with the
population labels) giving the number of allele copies (for an unfolded
spectrum, copies of the derived allele: the alternate allele, unless
the loci were polarised with ancestral, in which case it is the
reference allele at loci whose ancestral allele is the alternate one;
for a folded spectrum, copies of the minor allele across all the
populations of the spectrum), n_sites, the number
of sites in that cell (a fractional number, as each locus is spread over
the cells by the projection), and masked, TRUE for the cells that are
masked (the corners, i.e. monomorphic sites, and for a folded spectrum
the cells that were folded out). The projection of each population is
stored in the attribute n_proj, and whether the spectrum is folded in
the attribute folded.
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
sfs <- example_gt %>% pop_sfs(n_proj = 4, type = "array")
tidy(sfs[[1]])
Draw an UpSet plot from a data frame of logical columns
Description
This is a minimalistic implementation of upset plots, as used to visualise
our qc_loci_report. It is not intended to be a general-purpose upset
plotting function, and it does not attempt to replicate all the features of
specialised packages. It produces a three-panel UpSet plot assembled with
patchwork:
-
Top panel - bar chart of intersection sizes, labelled.
-
Matrix panel - dot-and-line membership matrix with alternating row backgrounds for readability.
-
Left panel - horizontal bar chart of per-set totals.
Usage
upset_plot(
df,
sets = NULL,
min_size = 1L,
n_intersections = 40L,
bar_colour = "#2166ac",
dot_colour = "#2166ac",
empty_colour = "#d9d9d9",
set_bar_colour = "#4dac26",
text_size = 11
)
Arguments
df |
A data frame with logical set-membership columns. |
sets |
Character vector of column names to use as sets.
Defaults to |
min_size |
Integer. Intersections with fewer than this many rows
are dropped. Default |
n_intersections |
Integer. Maximum number of intersections to display
(top-n by count). Default |
bar_colour |
Fill colour for the intersection size bars.
Default |
dot_colour |
Colour for filled dots and connecting lines in the
membership matrix. Default |
empty_colour |
Colour for absent-set dots in the matrix.
Default |
set_bar_colour |
Fill colour for the set-size bars.
Default |
text_size |
Base font size (pts) passed to all
|
Value
A patchwork object. Print it or pass it to
ggsave.
Examples
set.seed(1)
df <- data.frame(
A = sample(c(TRUE, FALSE), 100, replace = TRUE),
B = sample(c(TRUE, FALSE), 100, replace = TRUE),
C = sample(c(TRUE, FALSE), 100, replace = TRUE)
)
upset_plot(df)
Mathematical predicates for vctrs_bigSNP vectors
Description
Provides support for the mathematical predicate functions
is.finite(), is.infinite(), and is.nan() on
vctrs_bigSNP vectors.
Usage
## S3 method for class 'vctrs_bigSNP'
vec_math(.fn, .x, ...)
Arguments
.fn |
Name of the mathematical function being dispatched. |
.x |
A |
... |
Unused additional arguments. |
Details
These methods are primarily required for compatibility with RStudio's object inspector and other tooling that may call mathematical predicates on custom vctrs classes.
All other Math-group generics are deliberately unsupported and will raise an error.
Value
A logical vector for is.finite(), is.infinite(), and
is.nan().
Detect runs of homozygosity using a sliding-window
Description
This function looks for runs of homozygosity in a diploid genome with the
sliding-window algorithm of PLINK 1.9 (--homozyg), with the same
parameters and defaults. It is implemented natively in C++: all individuals
are analysed in a single pass over the genotypes.
Usage
windows_indiv_roh(.x, ...)
## S3 method for class 'gen_tbl'
windows_indiv_roh(
.x,
window_snp = 50,
window_het = 1,
window_missing = 5,
window_threshold = 0.05,
min_snp = 100,
min_kb = 1000,
max_kb_per_snp = 50,
max_gap_kb = 1000,
max_het = Inf,
subtract_1_from_lengths = FALSE,
n_cores = bigstatsr::nb_cores(),
...
)
Arguments
.x |
a |
... |
other arguments passed to specific methods. The method for
|
window_snp |
the number of loci in each window (PLINK
|
window_het |
the largest number of heterozygous genotypes in a window
that is a hit (PLINK |
window_missing |
the largest number of missing genotypes in a window
that is a hit (PLINK |
window_threshold |
the smallest proportion of the windows that
include a locus that must be hits for the locus to be in a run (PLINK
|
min_snp |
the smallest number of loci in a run (PLINK |
min_kb |
the smallest length of a run, in kb (PLINK |
max_kb_per_snp |
the largest average distance between the loci of a
run, in kb per locus, i.e. the inverse of its smallest density (PLINK
|
max_gap_kb |
the largest gap between two consecutive loci of a run, in
kb: a larger gap breaks a run (PLINK |
max_het |
the largest number of heterozygous genotypes in a run
(PLINK |
subtract_1_from_lengths |
if |
n_cores |
the number of cores to use (individuals are analysed in parallel) |
Details
On each chromosome, a window of window_snp consecutive loci starts at
each locus (except the last window_snp - 1). A window is a hit if it has
at most window_het heterozygous and at most window_missing missing
genotypes. A locus is in a run if at least a proportion window_threshold
(rounded up) of the windows that include it are hits. Runs are stretches of
consecutive loci in a run, which are broken where the gap between two loci
is larger than max_gap_kb, and before the heterozygous genotype that
would exceed max_het. Runs are returned if they have at least min_snp
loci, a length of at least min_kb, and at most max_kb_per_snp kb per
locus.
The runs are those of plink --homozyg with the same parameters,
including the features of its algorithm:
windows restart at each chromosome, so a chromosome with fewer loci than
window_snphas no runs; windows can span large gaps, which only break runs;the number of windows used for the threshold of the last
window_snp - 1loci of a chromosome is the number of loci to its end (which, on chromosomes with fewer than2 * window_snp - 2loci, is more than the number of windows that include the locus);runs are not trimmed, so they can start or end with heterozygous or missing genotypes; missing genotypes in a run are not limited.
Genotypes are classified by their dosage (1 is heterozygous, 0 and 2 are
homozygous). Unlike PLINK, all chromosomes are analysed: PLINK skips
haploid chromosomes (e.g. Y and MT), and male X chromosomes. Remove them
first (e.g. with select_loci()) to get the same runs. PLINK has no
runs of heterozygosity; gt_roh_window() (based on detectRUNS) can
still find them. The loci must be sorted by chromosome and position (see
gt_order_loci()).
Runs can be plotted with autoplot.indiv_roh(), which draws the plots
of detectRUNS. Use as_detectRUNS() to convert the runs to the format
of detectRUNS, to use its own functions.
windows_indiv_roh() is an S3 generic, with a method for gen_tibble
objects (grouped or not). Other packages can add methods for their own
classes (e.g. tibbles of genotype likelihoods).
Value
An indiv_roh object, a tibble with one row per run, ordered by
individual, then by chromosome (in the order of its levels) and
position, with columns:
the grouping variable(s), if the
gen_tibbleis grouped (a singlegroupcolumn for one grouping variable, keeping its type, or one column per grouping variable);-
id: the individual; -
chromosome: the chromosome of the run (a factor, with the levels of the loci table; integer chromosomes, fromchromosomes_as_int = TRUE, are replaced by their names from the chromosome sidecar, seegt_lookup_chromosomes(), so the runs are the same as withoutchromosomes_as_int); -
start,end: the positions of the first and last locus of the run (in bp; PLINKPOS1andPOS2); -
length_bp:end - start + 1(orend - startwithsubtract_1_from_lengths = TRUE; PLINKKBx 1000); -
n_loci: the number of loci in the run (PLINKNSNP); -
first_locus,last_locus: the rows of the first and last locus of the run in the loci table (show_loci()); -
n_het: the number of heterozygous genotypes in the run (PLINKPHETxNSNP); -
n_missing: the number of missing genotypes in the run.
Its attributes individuals (a tibble of all the individuals, with
their groups, including those with no run), chromosome_length (the
length of each chromosome, its largest position, as in detectRUNS) and
n_loci (the number of loci) are used by autoplot.indiv_roh(),
gt_roh_froh(), gt_roh_loci() and gt_roh_islands().
References
Chang CC, Chow CC, Tellier LCAM, Vattikuti S, Purcell SM, Lee JJ (2015) Second-generation PLINK: rising to the challenge of larger and richer datasets. GigaScience, 4. doi:10.1186/s13742-015-0047-8
Examples
# a simulated dataset of three populations with increasing inbreeding
# (see data-raw/create_roh_dataset.R in the source of the package)
bed_file <- system.file("extdata", "roh", "roh_sim.bed",
package = "tidypopgen"
)
sim_gt <- gen_tibble(bed_file, backingfile = tempfile(), quiet = TRUE)
sim_gt <- sim_gt %>% group_by(population)
sim_roh <- windows_indiv_roh(sim_gt)
sim_roh
# the number of runs in each population
table(sim_roh$group)
# use the plots of detectRUNS
if (rlang::is_installed("detectRUNS")) {
detectRUNS::plot_Runs(runs = as_detectRUNS(sim_roh))
}
Compute the Population Branch Statistics over a sliding window
Description
The function computes the population branch statistics (PBS) for a sliding window for each combination of populations at each locus. The PBS is a measure of the genetic differentiation between one focal population and two reference populations, and is used to identify outlier loci that may be under selection.
Usage
windows_nwise_pop_pbs(.x, ...)
## S3 method for class 'gen_tbl'
windows_nwise_pop_pbs(
.x,
type = c("matrix", "tidy"),
fst_method = c("Hudson", "Nei87", "WC84"),
return_fst = FALSE,
window_size,
step_size,
size_unit = c("snp", "bp"),
min_loci = 1,
complete = FALSE,
...
)
Arguments
.x |
a grouped |
... |
other arguments passed to specific methods, currently unused. |
type |
type of object to return. One of "matrix" or "tidy". Default is "matrix". "matrix" returns a dataframe where each row is a window, followed by columns of pbs values for each population comparison. "tidy" returns a tidy tibble of the same data in 'long' format, where each row is one window for one population comparison. |
fst_method |
the method to use for calculating Fst, one of 'Hudson',
'Nei87', and 'WC84'. See |
return_fst |
a logical value indicating whether to return the Fst values |
window_size |
The size of the window to use for the estimates. |
step_size |
The step size to use for the windows. |
size_unit |
Either "snp" or "bp". If "snp", the window size and step size are in number of SNPs. If "bp", the window size and step size are in base pairs. |
min_loci |
The minimum number of loci required to calculate a window statistic. If the number of loci in a window is less than this, the window statistic will be NA. |
complete |
Should the function be evaluated on complete windows only? If FALSE, the default, then partial computations will be allowed at the end of the chromosome. |
Value
either a data frame with the following columns:
-
chromosome: the chromosome for the window -
start: the starting locus of the window -
end: the ending locus of the window -
pbs_a.b.c: the PBS value for population a given b & c (there will be multiple such columns covering all 3 way combinations of populations in the groupedgen_tibbleobject) -
fst_a.b: the Fst value for population a and b, ifreturn_fstis TRUE or a tidy tibble with the following columns: -
chromosome: the chromosome for the window -
start: the starting locus of the window -
end: the ending locus of the window -
stat_name: the name of populations used in the pbs calculation (e.g. "pbs_pop1.pop2.pop3"). If return_fst is TRUE, stat_name will also include "fst" calculations in the same column (e.g. "fst_pop1.pop2"). -
value: the pbs value for the populations
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Calculate nwise pbs across a window of 3 SNPs, with a step size of 2 SNPs
example_gt %>%
windows_nwise_pop_pbs(
window_size = 3, step_size = 2,
size_unit = "snp", min_loci = 2
)
Compute pairwise Fst for a sliding window
Description
This function computes pairwise Fst for a sliding window across each chromosome.
Usage
windows_pairwise_pop_fst(.x, ...)
## S3 method for class 'gen_tbl'
windows_pairwise_pop_fst(
.x,
type = c("matrix", "tidy"),
method = c("Hudson", "Nei87", "WC84"),
window_size,
step_size,
size_unit = c("snp", "bp"),
min_loci = 1,
complete = FALSE,
...
)
Arguments
.x |
a grouped |
... |
other arguments passed to specific methods, currently unused. |
type |
type of object to return. One of "matrix" or "tidy". Default is "matrix". "matrix" returns a dataframe where each row is a window, followed by columns of Fst values for each pairwise population a and b comparison. "tidy" returns a tidy tibble of the same data in 'long' format, where each row is one window for one pairwise population a and b comparison. |
method |
the method to use for calculating Fst, one of 'Hudson',
'Nei87', and 'WC84'. See |
window_size |
The size of the window to use for the estimates. |
step_size |
The step size to use for the windows. |
size_unit |
Either "snp" or "bp". If "snp", the window size and step size are in number of SNPs. If "bp", the window size and step size are in base pairs. |
min_loci |
The minimum number of loci required to calculate a window statistic. If the number of loci in a window is less than this, the window statistic will be NA. |
complete |
Should the function be evaluated on complete windows only? If FALSE, the default, then partial computations will be allowed at the end of the chromosome. |
Value
either a data frame with the following columns:
-
chromosome: the chromosome for the window -
start: the starting locus of the window -
end: the ending locus of the window -
fst_a.b: the pairwise Fst value for the population a and b (there will be multiple such columns if there are more than two populations) or a tidy tibble with the following columns: -
chromosome: the chromosome for the window -
start: the starting locus of the window -
end: the ending locus of the window -
stat_name: the name of population a and b used in the pairwise Fst calculation (e.g. "fst_pop1.pop2") -
value: the pairwise Fst value for the population a and b
Examples
example_gt <- load_example_gt("gen_tbl")
example_gt %>%
group_by(population) %>%
windows_pairwise_pop_fst(
window_size = 3, step_size = 2,
size_unit = "snp", min_loci = 2
)
Compute Tajima's D for a sliding window
Description
This function computes Tajima's D for a sliding window across each chromosome.
Usage
windows_pop_tajimas_d(.x, ...)
## S3 method for class 'gen_tbl'
windows_pop_tajimas_d(
.x,
type = c("matrix", "tidy", "list"),
window_size,
step_size,
size_unit = c("snp", "bp"),
min_loci = 1,
complete = FALSE,
...
)
Arguments
.x |
a (potentially grouped) |
... |
other arguments passed to specific methods, currently unused. |
type |
type of object to return, if using grouped method. One of
"matrix", "tidy", or "list". Default is "matrix".
Data can be grouped by more than one variable: groups are then labelled
by the values of the grouping variables pasted with "." (e.g. |
window_size |
The size of the window to use for the estimates. |
step_size |
The step size to use for the windows. |
size_unit |
Either "snp" or "bp". If "snp", the window size and step size are in number of SNPs. If "bp", the window size and step size are in base pairs. |
min_loci |
The minimum number of loci required to calculate a window statistic. If the number of loci in a window is less than this, the window statistic will be NA. |
complete |
Should the function be evaluated on complete windows only? If FALSE, the default, then partial computations will be allowed at the end of the chromosome. |
Details
Missing genotypes are accounted for by using the number of
non-missing allele copies at each locus as its sample size, following
Bailey et al. (2025) as implemented in pixy. See pop_tajimas_d() for
details. Loci with no genotyped individuals are ignored, and are not
counted in n_loci. With windows defined in base pairs and
step_size equal to window_size, the windows match those used by
pixy.
Value
if data is not grouped, a data frame with the following columns:
-
chromosome: the chromosome for the window -
start: the starting locus of the window -
end: the ending locus of the window -
tajimas_d: the Tajima's D for the population if data are grouped, either: a data frame as above with the following columns: -
chromosome: the chromosome for the window -
start: the starting locus of the window -
end: the ending locus of the window -
n_loci: the number of loci in the window (including loci with no genotyped individuals in some groups; the number of loci with data in each group is given by the "tidy" and "list" outputs) -
group: the Tajima's D for the group for the given window (there will be as many of these columns as groups in the gen_tibble, and they will be named by the grouping levels) a tidy tibble with the following columns: -
chromosome: the chromosome for the window -
start: the starting locus of the window -
end: the ending locus of the window -
n_loci: the number of loci in the window -
group: the name of the group -
stat: the Tajima's D for the given group at the given window or a list of data frames, one per group, with the following columns: -
chromosome: the chromosome for the window -
start: the starting locus of the window -
end: the ending locus of the window -
stat: the Tajima's D for the given window -
n_loci: the number of loci in the window
References
Bailey N, Stevison L, Samuk K (2025) Correcting for bias in
estimates of \theta_W and Tajima's D from missing data in
next-generation sequencing. Molecular Ecology Resources, e14104.
doi:10.1111/1755-0998.14104
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# Calculate Tajima's D across a window of 3 SNPs, with a step size of 2 SNPs
example_gt %>%
windows_pop_tajimas_d(
window_size = 3, step_size = 2,
size_unit = "snp", min_loci = 2
)
Estimate window statistics from per locus estimates
Description
This function is mostly designed for developers: it is a general function to
estimate window statistics from per locus estimates. This function takes a
vector of per locus estimates, and aggregates them by sum or mean per window.
To compute specific quantities directly from a gen_tibble, use the
appropriate window_* functions, e.g windows_pairwise_pop_fst() to compute
pairwise Fst.
Usage
windows_stats_generic(
.x,
loci_table,
operator = c("mean", "sum", "custom"),
window_size,
step_size,
size_unit = c("snp", "bp"),
min_loci = 1,
complete = FALSE,
f = NULL,
...
)
Arguments
.x |
A vector containing the per locus estimates. |
loci_table |
a dataframe including at least a column 'chromosome', and
additionally a column 'position' if |
operator |
The operator to use for the window statistics. Either "mean",
"sum" or "custom" to use a custom function |
window_size |
The size of the window to use for the estimates. |
step_size |
The step size to use for the windows. |
size_unit |
Either "snp" or "bp". If "snp", the window size and step size are in number of SNPs. If "bp", the window size and step size are in base pairs. |
min_loci |
The minimum number of loci required to calculate a window statistic. If the number of loci in a window is less than this, the window statistic will be NA. |
complete |
Should the function be evaluated on complete windows only? If FALSE, the default, then partial computations will be allowed at the end of the chromosome. |
f |
a custom function to use for the window statistics. This function should take a vector of locus estimates and return a single value. |
... |
Additional arguments to be passed to the custom operator function. |
Value
A tibble with columns: 'chromosome', 'start', 'end', 'stats', and 'n_loci'. The 'stats' column contains the mean of the per locus estimates in the window, and 'n_loci' contains the number of loci in the window.
Examples
example_gt <- load_example_gt("gen_tbl")
miss_by_locus <- loci_missingness(example_gt)
# Calculate mean missingness across windows
windows_stats_generic(miss_by_locus,
loci_table = show_loci(example_gt),
operator = "mean", window_size = 1000,
step_size = 1000, size_unit = "bp",
min_loci = 1, complete = FALSE
)
Write site frequency spectra for dadi or fastsimcoal2
Description
Write site frequency spectra in the formats used by dadi (and moments)
and by fastsimcoal2, as written by easySFS:
for an
sfsobject (as returned bypop_sfs(),pairwise_pop_sfs()andnwise_pop_sfs()withtype = "array", or by thebootstrap_*functions, e.g.bootstrap_pop_sfs()), write that spectrum tofile;for a grouped
gen_tibble, compute all the spectra thateasySFSwrites (the 1D spectrum of each population, the joint spectrum of each pair of populations, and the joint spectrum of all populations, in a single pass over the genotypes), and write them inout_dir, with the file names ofeasySFS, optionally with bootstrap replicates. Missing genotypes are dealt with by projecting each population down ton_projallele copies (seepop_sfs()).
Usage
write_sfs(x, ...)
## S3 method for class 'sfs'
write_sfs(
x,
file,
format = c("dadi", "fastsimcoal2", "fastsimcoal2_multidimensional"),
fastest = c("last", "first"),
total_length = NULL,
round = FALSE,
overwrite = FALSE,
...
)
## S3 method for class 'gen_tbl'
write_sfs(
x,
out_dir = NULL,
format = c("dadi", "fastsimcoal2"),
n_proj = NULL,
prefix = NULL,
folded = TRUE,
ancestral = NULL,
total_length = NULL,
round = FALSE,
fastest = c("last", "first"),
n_bootstrap = 0,
bootstrap_block_size = NULL,
bootstrap_size_unit = c("snp", "cM", "bp"),
max_cells = 1e+07,
overwrite = FALSE,
n_cores = bigstatsr::nb_cores(),
block_size = bigstatsr::block_size(nrow(x), 1),
...
)
## Default S3 method:
write_sfs(x, ...)
Arguments
x |
an |
... |
further arguments passed to the methods. |
file |
for an |
format |
the format of the files: |
fastest |
the order of the cells in dadi files and in the
multidimensional fastsimcoal2 format: "last" (the default) keeps the order
of the populations, so that the number of allele copies in the last
population changes fastest, as in |
total_length |
the total number of sites sequenced, including
monomorphic ones, used to set the number of monomorphic sites (the first
cell). If |
round |
boolean, whether to round the number of sites in each cell to
the nearest integer (as |
overwrite |
boolean, whether to overwrite files that already exist.
Defaults to |
out_dir |
for a |
n_proj |
the number of allele copies to project each population to:
either a single value used for all populations, a vector with one value
per population (in the order of the groups), or a vector named with the
group labels. If |
prefix |
for a |
folded |
boolean, whether to fold the spectrum (the default, as the
ancestral allele is not usually known). If |
ancestral |
the ancestral allele of each locus, used to polarise
unfolded spectra: either the name of a column of the loci table (see
|
n_bootstrap |
for a |
bootstrap_block_size, bootstrap_size_unit |
for a |
max_cells |
for a |
n_cores |
number of cores to be used, it defaults to
|
block_size |
maximum number of loci read at once. |
Details
dadi format (format = "dadi"): a line with the dimensions of the
spectrum (the number of allele copies of each population plus 1),
folded or unfolded and the population labels in quotes; a line with
the cells of the spectrum; and a line with the mask (1 for masked cells,
see pop_sfs()). In dadi files, the cells are listed with the number of
copies in the last population changing fastest. With fastest = "first",
the populations are written in reverse order, so that the number of
copies in the first population changes fastest and the file is still a
valid dadi file.
fastsimcoal2 format (format = "fastsimcoal2"): for a 1D spectrum,
as a _DAFpop0.obs (unfolded) or _MAFpop0.obs (folded) file; for a 2D
spectrum, as a _jointDAFpop1_0.obs or _jointMAFpop1_0.obs file, a
matrix with the second population in the rows (labelled d1_0, d1_1,
...) and the first population in the columns (labelled d0_0, d0_1,
...); for a spectrum of three or more populations, as a multidimensional
spectrum (_MSFS.obs file). For an sfs object,
format = "fastsimcoal2_multidimensional" writes the multidimensional
format whatever the number of populations. In the multidimensional
format, the cells are listed in the order set by
fastest: "last" (the default) has the number of copies in the last
population changing fastest, as written by easySFS; "first" has the
first population changing fastest. Please check which order your version
of fastsimcoal2 expects.
Monomorphic sites. As in easySFS, total_length gives the total
number of sites sequenced (including monomorphic sites that are not in
the gen_tibble): the first cell of the spectrum (sites with no copies of
the alternate or minor allele) is then set to total_length minus the
number of sites in all the other cells.
The spectra of a gen_tibble are written in out_dir, with the file
names of easySFS (pop stands for the population labels, p for their
projections, and M is replaced by D for unfolded spectra):
dadi:
pop-p.sfsfor each population,pop1-pop2.sfsfor each pair, andpop1-pop2-...-popK.sfsfor all populations;fastsimcoal2:
pop_MAFpop0.obsfor each population,prefix_jointMAFpopj_i.obsfor each pair (whereiandjare the 0-based indices of the two populations, so that the second population of the pair is in the rows), andprefix_MSFS.obsfor all populations.
easySFS writes these files in the sub-directories dadi and
fastsimcoal2 of its output directory: use, for example,
out_dir = file.path(dir, "dadi") with format = "dadi" and
out_dir = file.path(dir, "fastsimcoal2") with format = "fastsimcoal2"
to get the same layout. Populations are in the order of the groups (see
dplyr::group_keys()): to change their order, which matters for dadi
and fastsimcoal2 (and is set with --order in easySFS), change the
order of the levels of the grouping variable (e.g. with factor()).
With n_bootstrap replicates of a block bootstrap (see
bootstrap_pop_sfs()), the spectra of each replicate are also written,
with the same file names, in the sub-directories bootstrap_1,
bootstrap_2, ... of out_dir, numbered with as many digits as
n_bootstrap (e.g. bootstrap_001 to bootstrap_100), which can be
used to estimate confidence intervals with fastsimcoal2. Replicates use
the same projections as the spectra of all loci, and total_length and
round are applied to each of them. To draw the same replicates in both
formats, set the same seed (with set.seed()) before writing each of
them.
Value
the path of the file (for an sfs object) or the paths of the
files written (for a gen_tibble), invisibly.
See Also
pop_sfs(), pop_sfs_preview(), bootstrap_pop_sfs()
Examples
example_gt <- load_example_gt("grouped_gen_tbl")
# write a single spectrum
sfs_2d <- example_gt %>%
pairwise_pop_sfs(n_proj = 2, type = "array")
dadi_file <- tempfile(fileext = ".sfs")
write_sfs(sfs_2d$pop1.pop2, dadi_file)
readLines(dadi_file)
fastsimcoal2_file <- tempfile(fileext = "_jointMAFpop1_0.obs")
write_sfs(sfs_2d$pop1.pop2, fastsimcoal2_file, format = "fastsimcoal2")
readLines(fastsimcoal2_file)
# write all the spectra written by easySFS, in the same directories
out_dir <- file.path(tempdir(), "example_sfs")
dadi_files <- example_gt %>%
write_sfs(out_dir = file.path(out_dir, "dadi"), n_proj = 2)
basename(dadi_files)
fastsimcoal2_files <- example_gt %>%
write_sfs(
out_dir = file.path(out_dir, "fastsimcoal2"), format = "fastsimcoal2",
n_proj = 2, prefix = "example"
)
basename(fastsimcoal2_files)
# with 3 bootstrap replicates, resampling blocks of 2 SNPs
set.seed(1)
fastsimcoal2_files <- example_gt %>%
write_sfs(
out_dir = file.path(out_dir, "fastsimcoal2"), format = "fastsimcoal2",
n_proj = 2, prefix = "example", n_bootstrap = 3,
bootstrap_block_size = 2, overwrite = TRUE
)
list.files(file.path(out_dir, "fastsimcoal2"))