### Install and load pcadapt Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Initial setup commands to install and load the pcadapt package in an R session. ```R install.packages("pcadapt") library(pcadapt) ``` -------------------------------- ### Install pcadapt from GitHub Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/index.html Use this command to install the latest development version of the pcadapt package directly from GitHub. ```r remotes::install_github("bcm-uga/pcadapt") ``` -------------------------------- ### Install and Load qvalue Package Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Provides commands to install the 'qvalue' package from Bioconductor and load it into the R session. Use this for q-value analysis. ```R source("https://bioconductor.org/biocLite.R") biocLite("qvalue") library(qvalue) ``` -------------------------------- ### Run pcadapt Shiny App Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/run.pcadapt.html Launches the Shiny interface for pcadapt. Ensure the package is installed and loaded before running. ```R run.pcadapt() ``` -------------------------------- ### Load Example Pooled Sequencing Data Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Loads a built-in example dataset of pooled sequencing data from the pcadapt package for demonstration or testing purposes. ```R path_to_file <- system.file("extdata", "pool3pops", package = "pcadapt") pool.data <- read.pcadapt(path_to_file, type = "pool") ``` -------------------------------- ### Install pcadapt from CRAN Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/index.html Use this command to install the pcadapt package from the Comprehensive R Archive Network (CRAN). ```r install.packages("pcadapt") ``` -------------------------------- ### GET get.pc Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/get.pc.html Retrieves a data frame mapping genetic markers to their most correlated principal component. ```APIDOC ## get.pc ### Description Returns a data frame where each row contains the index of the genetic marker and the principal component most correlated with it. ### Parameters #### Arguments - **x** (pcadapt object) - Required - An object of class 'pcadapt'. - **list** (integer vector) - Required - A list of integers corresponding to the indices of the markers of interest. ### Response - **data.frame** - A data frame containing the marker index and the index of the most associated principal component. ``` -------------------------------- ### Get Statistics Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/get_statistics.html Computes chi-squared distributed statistics using provided z-scores and a specified method. ```APIDOC ## GET /statistics/get_statistics ### Description Returns chi-squared distributed statistics. ### Method GET ### Endpoint /statistics/get_statistics ### Parameters #### Query Parameters - **zscores** (numeric matrix) - Required - A numeric matrix containing the z-scores. - **method** (character string) - Required - Specifies the method to be used to compute the p-values. Two statistics are currently available, "mahalanobis", and "componentwise". - **pass** (boolean vector) - Required - A boolean vector. ### Response #### Success Response (200) - **statistics** (list) - A list containing the test statistics and the associated p-values. ``` -------------------------------- ### Get Score Color Function Signature Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/get.score.color.html This is the function signature for get.score.color. It takes a single argument 'pop' which specifies the population each individual belongs to. ```R get.score.color(pop) ``` -------------------------------- ### run.pcadapt() Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/index.html Launches the Shiny application for pcadapt. ```APIDOC ## run.pcadapt() ### Description Shiny app. ### Method Function call ``` -------------------------------- ### Launch pcadapt Shiny App Source: https://context7.com/bcm-uga/pcadapt/llms.txt Launches an interactive Shiny web application for pcadapt analysis, providing a graphical user interface for data loading, parameter selection, and result exploration. ```R library(pcadapt) # Launch the Shiny app run.pcadapt() # The app opens in your default web browser # Features include: # - File upload for various genotype formats # - Interactive parameter selection (K, min.maf, etc.) # - Real-time scree plots and score plots # - Manhattan plots with zoom capability # - Export results to CSV # Alternative: calling pcadapt() without arguments also launches the app # pcadapt() ``` -------------------------------- ### Compute pcadapt with K Principal Components Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Initialize the pcadapt analysis by specifying the number of principal components (K) to use. This step is crucial before computing test statistics. ```R x <- pcadapt(filename, K = 2) ``` -------------------------------- ### Write PLINK Bed Files with writeBed Source: https://context7.com/bcm-uga/pcadapt/llms.txt Demonstrates how to write PLINK bed, bim, and fam files from pcadapt or lfmm format files. This function is typically called internally by read.pcadapt but can be used directly. ```R library(pcadapt) # writeBed is typically called internally by read.pcadapt # When you call read.pcadapt on a pcadapt or lfmm file, # it automatically creates a corresponding .bed file pcadapt_file <- system.file("extdata", "geno3pops.pcadapt", package = "pcadapt") # This creates geno3pops.pcadapt.bed, .bim, and .fam files input <- read.pcadapt(pcadapt_file, type = "pcadapt") # The bed file is created in the same directory as the input # bed_path: /path/to/geno3pops.pcadapt.bed # Direct usage of writeBed (internal function, typically not called directly) # bed_output <- writeBed(pcadapt_file, is.pcadapt = TRUE) # For lfmm files: # bed_output <- writeBed(lfmm_file, is.pcadapt = FALSE) ``` -------------------------------- ### read.pcadapt() Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/index.html File converter for pcadapt input files. ```APIDOC ## read.pcadapt() ### Description File Converter. ### Method Function call ``` -------------------------------- ### Get Outlier SNP Indices and Filter by Effect Size Source: https://context7.com/bcm-uga/pcadapt/llms.txt Retrieve the indices of outlier SNPs identified by a chosen method (e.g., BH) and optionally filter them further based on their effect size. ```r # Get SNP indices of outliers outlier_snps <- outliers_bh cat("Outlier SNP indices:", head(outlier_snps), "...\n") # Filter outliers by effect size (optional) strong_outliers <- outliers_bh[abs(x$stat[outliers_bh]) > quantile(x$stat, 0.99, na.rm = TRUE)] ``` -------------------------------- ### Load and Run pcadapt Analysis Source: https://context7.com/bcm-uga/pcadapt/llms.txt Load genetic data from a BED file and perform a PCA-based analysis. Ensure the 'pcadapt' library is loaded. ```r library(pcadapt) path_to_file <- system.file("extdata", "geno3pops.bed", package = "pcadapt") filename <- read.pcadapt(path_to_file, type = "bed") x <- pcadapt(filename, K = 2) ``` -------------------------------- ### Run pcadapt with Direct Frequency Matrix Input Source: https://context7.com/bcm-uga/pcadapt/llms.txt Provide allele frequency data directly as an R matrix to pcadapt. The matrix should have populations as rows and SNPs as columns, with values representing allele frequencies. This is an alternative to reading from a file. ```r # For Pool-seq, you can also provide an R matrix directly # Rows = populations, Columns = SNPs, Values = allele frequencies freq_matrix <- matrix(runif(300), nrow = 3, ncol = 100) pool_input <- read.pcadapt(freq_matrix, type = "pool") res <- pcadapt(pool_input, K = 2) ``` -------------------------------- ### Load and Analyze Pool-Seq Data with pcadapt Source: https://context7.com/bcm-uga/pcadapt/llms.txt Demonstrates how to load pool-sequencing data and perform a principal component analysis using pcadapt. This is useful for identifying genetic differentiation in pooled samples. ```R pool_file <- system.file("extdata", "pool3pops", package = "pcadapt") pool_data <- read.pcadapt(pool_file, type = "pool") res_pool <- pcadapt(pool_data, K = 2) pool_pc <- get.pc(res_pool, 1:150) print(pool_pc$PC) ``` -------------------------------- ### plot.pcadapt() Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/index.html Visualization tool for pcadapt results. ```APIDOC ## plot(pcadapt) ### Description pcadapt visualization tool. ### Method Function call ``` -------------------------------- ### Load and Run pcadapt on Pool-seq Data Source: https://context7.com/bcm-uga/pcadapt/llms.txt Load Pool-seq data using read.pcadapt and run the pcadapt analysis. K defaults to n_populations - 1. Ensure the path to the data file is correct. ```r library(pcadapt) # Load Pool-seq example data path_to_file <- system.file("extdata", "pool3pops", package = "pcadapt") pool_data <- read.pcadapt(path_to_file, type = "pool") # Run pcadapt on Pool-seq data # K defaults to n_populations - 1 res_pool <- pcadapt(pool_data, K = 3) ``` -------------------------------- ### Perform PCA with pcadapt Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Run the pcadapt function to perform PCA and compute test statistics. A large number of components (e.g., K=20) is recommended initially to help determine the optimal K. ```R x <- pcadapt(input = filename, K = 20) ``` -------------------------------- ### Run pcadapt on in-memory matrices Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Load genotype data from memory and execute pcadapt analysis. ```R path_to_file <- system.file("extdata", "SSMPG2017.rds", package = "pcadapt") genotypes <- readRDS(path_to_file) print(dim(genotypes)) matrix <- read.pcadapt(genotypes, type = "pcadapt") res <- pcadapt(matrix, K = 20) plot(res, option = "screeplot") ``` -------------------------------- ### Write PLINK files using writeBed Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/writeBed.html The writeBed function allows you to convert pcadapt or lfmm files into PLINK format (bed, bim, fam). ```APIDOC ## writeBed ### Description Function to write bed/bim/fam files from a pcadapt or an lfmm file. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters #### Arguments - **file** (character) - A pcadapt or lfmm file. - **is.pcadapt** (boolean) - A boolean value indicating if the input file is in pcadapt format. ### Value - The input `bedfile` path (character). ``` -------------------------------- ### writeBed() Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/index.html Writes data to PLINK bed file format. ```APIDOC ## writeBed() ### Description Write PLINK files. ### Method Function call ``` -------------------------------- ### Accessing pcadapt Results Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Demonstrates how to access various numerical quantities from the output object 'x' of the pcadapt function using the '$' symbol. ```R summary(x) ``` ```R x$pvalues ``` -------------------------------- ### plot.pcadapt Function Documentation Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/plot.pcadapt.html Documentation for the plot.pcadapt S3 method, used for visualizing pcadapt objects. ```APIDOC ## plot.pcadapt ### Description This S3 method is designed for objects of class `pcadapt` and provides plotting options for quick visualization. It supports several plot types including screeplot, scores, stat.distribution, manhattan, and qqplot. ### Method S3 method for `pcadapt` objects ### Endpoint N/A (This is an R function, not a web API endpoint) ### Parameters #### Arguments - **x** (object of class "pcadapt") - The pcadapt object generated with `pcadapt`. - **...** (...) - Additional arguments. - **option** (character string) - Specifies the figures to be displayed. Options include: "screeplot", "scores", "stat.distribution", "manhattan", "qqplot". If NULL, all plots are printed. Default is "manhattan". - **i** (integer) - The principal component onto which individuals are projected when the "scores" option is chosen. Default is 1. - **j** (integer) - The principal component onto which individuals are projected when the "scores" option is chosen. Default is 2. - **pop** (list of integers or strings) - Specifies which subpopulation the individuals belong to. - **col** (list of colors) - Colors to be used in the score plot. - **chr.info** (list) - Contains the chromosome information for each marker. - **snp.info** (list) - Contains the names of all genetic markers present in the input. - **plt.pkg** (character string) - Specifies the package to be used for graphical outputs. Use "plotly" for interactive plots, or "ggplot" for static plots. Default is "ggplot". - **K** (integer) - The principal component of interest. Only required when using the "componentwise" method. ### Request Example N/A (This is an R function, not a web API endpoint) ### Response N/A (This function generates plots, not a structured response) ### Error Handling N/A ``` -------------------------------- ### print_convert Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/print_convert.html Prints out a summary of the file conversion process for genotype or pooled data. ```APIDOC ## print_convert ### Description Prints out a summary of the file conversion. ### Parameters #### Arguments - **input** (matrix/string) - Required - A genotype matrix or a character string specifying the name of the file to be converted. - **output** (string) - Required - A character string specifying the name of the output file. - **M** (integer) - Required - The number of genetic markers present in the data. - **N** (integer) - Required - The number of individuals present in the data. - **pool** (integer) - Required - The type of data: 0 for genotype data, 1 for pooled data. ``` -------------------------------- ### Visualize pcadapt results Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Generate diagnostic plots for pcadapt objects. ```R plot(res, option = "screeplot") ``` ```R plot(res, option = "manhattan") ``` -------------------------------- ### Access and Visualize Component-wise P-values Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Demonstrates how to access individual component p-values and plot the distribution of test statistics for component-wise analysis. The 'stat.distribution' option visualizes the neutral distribution, and K must be specified. ```R plot(x_cw, option = "stat.distribution", K = 2) ``` -------------------------------- ### Usage of get.pc function Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/get.pc.html Call get.pc with a pcadapt object and a list of marker indices to retrieve correlation data. ```R get.pc(x, list) ``` -------------------------------- ### Convert VCF files using vcf2pcadapt Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/vcf2pcadapt.html Use this function to convert VCF files to the pcadapt format. This tool is no longer maintained and users are encouraged to use PLINK instead. ```R vcf2pcadapt(input, output = "tmp.pcadapt", allele.sep = c("/", "|")) ``` -------------------------------- ### read.pcadapt Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/read.pcadapt.html Converts genotype matrices or files into formats readable by pcadapt. ```APIDOC ## read.pcadapt ### Description Converts genotype matrices or files to an appropriate format readable by pcadapt. For a file as input, you can choose to return either a matrix or convert it into bed/bim/fam files. ### Parameters #### Arguments - **input** (matrix or character) - Required - A genotype matrix or a character string specifying the name of the file to be converted. - **type** (character) - Optional - A character string specifying the type of data to be converted from (pcadapt, lfmm, vcf, bed, ped, pool, example). - **type.out** (character) - Optional - Either a bed file or a standard R matrix. - **allele.sep** (vector) - Optional - A vector of characters indicating what delimiters are used in VCF files. ``` -------------------------------- ### pcadapt() Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/index.html Performs Principal Component Analysis for outlier detection. ```APIDOC ## pcadapt() ### Description Principal Component Analysis for outlier detection. ### Method Function call ``` -------------------------------- ### Analyze Pool-Seq Data with pcadapt Source: https://context7.com/bcm-uga/pcadapt/llms.txt Read and analyze pool-sequencing data. The K parameter defaults to n_populations - 1 if not specified. ```r pool_file <- system.file("extdata", "pool3pops", package = "pcadapt") pool_data <- read.pcadapt(pool_file, type = "pool") res_pool <- pcadapt(pool_data, K = 3) ``` -------------------------------- ### Summarize and Plot pcadapt Results Source: https://context7.com/bcm-uga/pcadapt/llms.txt View a summary of the pcadapt analysis results and generate a scree plot to visualize the proportion of variance explained by each principal component. Note that the scree plot may not be informative with a small number of populations. ```r # View summary summary(res_pool) # Scree plot (may not be informative with few populations) plot(res_pool, option = "screeplot") ``` -------------------------------- ### Compute pcadapt with Minimum Minor Allele Frequency Threshold Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Run the pcadapt analysis while setting a minimum minor allele frequency (min.maf) threshold. SNPs with MAF below this threshold will have their p-values reported as NA. ```R x <- pcadapt(filename, K = 2, min.maf = 0.05) ``` -------------------------------- ### Generate Q-Q Plot Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Generates a Q-Q plot to compare the observed p-values against their expected uniform distribution. Requires the 'pcadapt' object 'x'. ```R plot(x, option = "qqplot") ``` -------------------------------- ### Visualize Loadings and Manhattan Plot Source: https://context7.com/bcm-uga/pcadapt/llms.txt Visualize the distribution of loadings for the first two principal components and display the Manhattan plot to identify potential adaptive signals. This is useful for an initial assessment of the PCA results. ```r par(mfrow = c(1, 2)) for (i in 1:2) { plot(res_final$loadings[, i], pch = 19, cex = 0.3, ylab = paste0("Loadings PC", i)) } plot(res_final, option = "manhattan") ``` -------------------------------- ### Define plot.pcadapt method signature Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/plot.pcadapt.html The S3 method signature for plotting pcadapt objects with various configuration options. ```R # S3 method for pcadapt plot( x, ..., option = "manhattan", i = 1, j = 2, pop, col, chr.info = NULL, snp.info = NULL, plt.pkg = "ggplot", K = NULL ) ``` -------------------------------- ### Perform PCA with LD Clumping and Plot Loadings Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Performs PCA with LD clumping and then plots the loadings for the first two principal components. This visualization helps assess the distribution of SNP contributions after LD thinning. ```R res <- pcadapt(matrix, K = 2, LD.clumping = list(size = 200, thr = 0.1)) par(mfrow = c(1, 2)) for (i in 1:2) plot(res$loadings[, i], pch = 19, cex = .3, ylab = paste0("Loadings PC", i)) ``` -------------------------------- ### Graphical Tools Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Provides functions for visualizing PCA results, including Manhattan plots, Q-Q plots, and histograms of test statistics and p-values. ```APIDOC ## Graphical Tools ### Manhattan Plot A Manhattan plot displays -log10 of the p-values. ```R plot(x , option = "manhattan") ``` ### Q-Q Plot The user can also check the expected uniform distribution of the p-values using a Q-Q plot. ```R plot(x, option = "qqplot") ``` This plot confirms that most of the p-values follow the expected uniform distribution. However, the smallest p-values are smaller than expected confirming the presence of outliers. ### Histograms of the test statistic and of the p-values An histogram of p-values confirms that most of the p-values follow an uniform distribution. The excess of small p-values indicates the presence of outliers. ```R hist(x$pvalues, xlab = "p-values", main = NULL, breaks = 50, col = "orange") ``` The presence of outliers is also visible when plotting a histogram of the test statistic DjD_j. ```R plot(x, option = "stat.distribution") ``` ``` -------------------------------- ### Convert ped files to pcadapt format Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/ped2pcadapt.html Use ped2pcadapt to convert input ped files to the pcadapt format. Specify the input and output file names. ```R ped2pcadapt(input, output) ``` -------------------------------- ### Calculate and Identify Outliers using q-values Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Calculates q-values from p-values and identifies SNPs with q-values below a specified alpha threshold, indicating potential outliers. Requires the 'qvalue' package and the 'pcadapt' object 'x'. ```R library(qvalue) qval <- qvalue(x$pvalues)$qvalues alpha <- 0.1 outliers <- which(qval < alpha) length(outliers) ``` -------------------------------- ### bed2matrix() Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/index.html Converts a PLINK bed file to a matrix format. ```APIDOC ## bed2matrix() ### Description Convert a bed to a matrix. ### Method Function call ``` -------------------------------- ### Read genotype data Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Convert genotype files to the required bed format using read.pcadapt. Supported formats include pcadapt, lfmm, vcf, bed, ped, and pool. ```R path_to_file <- "path_to_directory/foo.lfmm" filename <- read.pcadapt(path_to_file, type = "lfmm") ``` ```R path_to_file <- system.file("extdata", "geno3pops.bed", package = "pcadapt") filename <- read.pcadapt(path_to_file, type = "bed") ``` -------------------------------- ### pcadapt Function Reference Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/pcadapt.html Reference for the pcadapt function, including its various methods and parameters for analyzing genetic data. ```APIDOC ## pcadapt Function ### Description Performs principal component analysis and computes p-values to test for outliers. The test for outliers is based on the correlations between genetic variation and the first K principal components. Handles Pool-seq data. ### Method S3 methods for different input types: `pcadapt_matrix`, `pcadapt_bed`, `pcadapt_pool`. ### Endpoint N/A (R function) ### Parameters #### input - **input** (object) - The output of function `read.pcadapt`. #### K - **K** (integer) - Specifies the number of principal components to retain. Default is 2. #### method - **method** (character string) - Specifies the method to be used to compute the p-values. Available options: `"mahalanobis"` (default), `"componentwise"`. Deprecated: `"communality"`. #### min.maf - **min.maf** (numeric) - Threshold of minor allele frequencies above which p-values are computed. Default is `0.05`. #### ploidy - **ploidy** (integer or NULL) - Number of trials, parameter of the binomial distribution. Default is 2 (diploid). For Pool-seq data, this can be NULL. #### LD.clumping - **LD.clumping** (list or NULL) - If not NULL, specifies parameters for SNP thinning. Should be a named list with `$size` (window radius) and `$thr` (squared correlation threshold). Default is `NULL`. #### pca.only - **pca.only** (logical) - If TRUE, returns only PCA results before statistic computation. Default is `FALSE`. #### tol - **tol** (numeric) - Convergence criterion for `RSpectra::svds()`. Default is `1e-4`. ### Value - Returns an object of class `pcadapt`. ### Details Performs PCA on scaled and centered genotype data. Computes test statistics based on the chosen `method`. - `"mahalanobis"`: Uses robust Mahalanobis distance based on z-scores and their covariance. - `"componentwise"`: Returns a matrix of z-scores. For `"mahalanobis"` method, scaled statistics (`chi2_stat`) should follow a chi-squared distribution with K degrees of freedom. For `"componentwise"`, z-scores should follow a chi-squared distribution with 1 degree of freedom. ### Request Example ```R # Example for matrix input # data_matrix <- read.pcadapt("your_data.geno", format = "geno", parallel = TRUE) # result_matrix <- pcadapt(data_matrix, K = 20, method = "mahalanobis") # Example for bed input # data_bed <- read.pcadapt("your_data.bed", format = "bed", parallel = TRUE) # result_bed <- pcadapt(data_bed, K = 20, method = "mahalanobis") # Example for pool input # data_pool <- read.pcadapt("your_data.pool", format = "pool", parallel = TRUE) # result_pool <- pcadapt(data_pool, K = 20, method = "mahalanobis") ``` ### Response #### Success Response (Object of class `pcadapt`) - **@data** (matrix) - Matrix of statistics. - **@chi2_stat** (numeric vector) - Chi-squared statistics. - **@gif** (numeric) - Genomic inflation factor. - **@pvalues** (numeric vector) - P-values. - **@loadings** (matrix) - Loadings of the principal components. - **@eigenvalues** (numeric vector) - Eigenvalues. - **@pcadapt** (list) - List containing intermediate results. #### Response Example ```R # Assuming 'result' is the output object from pcadapt() # print(result) # summary(result) ``` ``` -------------------------------- ### Visualize P-value Distribution Source: https://context7.com/bcm-uga/pcadapt/llms.txt Create a histogram to visualize the distribution of raw p-values obtained from the pcadapt analysis. This can help in assessing the overall significance. ```r # Examine p-value distribution hist(x$pvalues, breaks = 50, col = "orange", xlab = "p-values", main = "P-value Distribution") ``` -------------------------------- ### Load and Read Genotype Data for pcadapt Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Loads genotype data from an RDS file and reads it into a matrix format suitable for pcadapt analysis. Assumes individuals are in columns and SNPs are in rows. ```R path_to_file <- system.file("extdata", "SSMPG2017.rds", package = "pcadapt") genotypes <- readRDS(path_to_file) matrix <- read.pcadapt(genotypes, type = "pcadapt") ``` -------------------------------- ### Perform Component-wise Genome Scan Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Reads genotype data and performs a component-wise genome scan using pcadapt. Ensure the path to the genotype file is correct. K specifies the number of principal components to consider. ```R path_to_file <- system.file("extdata", "geno3pops.bed", package = "pcadapt") filename <- read.pcadapt(path_to_file, type = "bed") x_cw <- pcadapt(filename, K = 2, method = "componentwise") summary(x_cw$pvalues) ``` -------------------------------- ### Run PCA-only Mode in pcadapt Source: https://context7.com/bcm-uga/pcadapt/llms.txt Use pca.only = TRUE to compute PCA results without calculating statistics. This is useful for initial exploration of population structure. ```r x_pca <- pcadapt(filename, K = 10, pca.only = TRUE) ``` -------------------------------- ### Perform PCA and Plot Results Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Performs PCA with a specified number of components (K=4) and plots the results, typically showing the distribution of individuals in the principal component space. ```R res <- pcadapt(matrix, K = 4) plot(res) ``` -------------------------------- ### Perform Genome Scan after LD Thinning Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Conducts a genome scan using pcadapt after applying SNP thinning due to LD. This analysis aims to identify regions involved in local adaptation. ```R plot(res) ``` -------------------------------- ### Generate a Scree Plot Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Displays the percentage of variance explained by each principal component. ```R plot(x, option = "screeplot") ``` -------------------------------- ### get.pc() Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/index.html Retrieves the principal component most associated with a genetic marker. ```APIDOC ## get.pc() ### Description Get the principal component the most associated with a genetic marker. ### Method Function call ``` -------------------------------- ### Component-wise Plots for Specific PCs Source: https://context7.com/bcm-uga/pcadapt/llms.txt Generate plots for specific principal components when using the 'componentwise' method. This allows for detailed examination of individual component effects. ```r # Component-wise plots require specifying K x_cw <- pcadapt(filename, K = 2, method = "componentwise") plot(x_cw, option = "manhattan", K = 1) # Manhattan plot for PC1 plot(x_cw, option = "stat.distribution", K = 2) # Distribution for PC2 plot(x_cw, option = "qqplot", K = 1) ``` -------------------------------- ### Perform PCA and outlier detection with pcadapt Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/pcadapt.html The primary function for running PCA and computing p-values. It supports different input types and statistical methods for outlier detection. ```R pcadapt( input, K = 2, method = "mahalanobis", min.maf = 0.05, ploidy = 2, LD.clumping = NULL, pca.only = FALSE, tol = 1e-04 ) ``` ```R # S3 method for pcadapt_matrix pcadapt( input, K = 2, method = c("mahalanobis", "componentwise"), min.maf = 0.05, ploidy = 2, LD.clumping = NULL, pca.only = FALSE, tol = 1e-04 ) ``` ```R # S3 method for pcadapt_bed pcadapt( input, K = 2, method = c("mahalanobis", "componentwise"), min.maf = 0.05, ploidy = 2, LD.clumping = NULL, pca.only = FALSE, tol = 1e-04 ) ``` ```R # S3 method for pcadapt_pool pcadapt( input, K = (nrow(input) - 1), method = "mahalanobis", min.maf = 0.05, ploidy = NULL, LD.clumping = NULL, pca.only = FALSE, tol ) ``` -------------------------------- ### Read Genotype Data with read.pcadapt Source: https://context7.com/bcm-uga/pcadapt/llms.txt Converts various genotype file formats or in-memory matrices into a format compatible with the pcadapt function. ```r library(pcadapt) # Read from a bed file (PLINK binary format) path_to_file <- system.file("extdata", "geno3pops.bed", package = "pcadapt") filename <- read.pcadapt(path_to_file, type = "bed") # Returns: pcadapt_bed object with n=150 individuals, p=1500 SNPs # Read from a pcadapt format file (individuals in columns, SNPs in rows) # Returns bed file by default for large datasets pcadapt_file <- system.file("extdata", "geno3pops.pcadapt", package = "pcadapt") input <- read.pcadapt(pcadapt_file, type = "pcadapt") # Read from lfmm format file (individuals in rows, SNPs in columns) # lfmm_file <- "path/to/data.lfmm" # input <- read.pcadapt(lfmm_file, type = "lfmm") # Read genotype matrix directly (individuals in columns, SNPs in rows) genotypes <- readRDS(system.file("extdata", "SSMPG2017.rds", package = "pcadapt")) matrix_input <- read.pcadapt(genotypes, type = "pcadapt") # For matrices with individuals in rows, SNPs in columns, use type = "lfmm" # Read Pool-seq data (populations x SNPs frequency matrix) pool_file <- system.file("extdata", "pool3pops", package = "pcadapt") pool_data <- read.pcadapt(pool_file, type = "pool") # Returns: pcadapt_pool object ready for population-level analysis # Convert to in-memory matrix instead of bed file input_matrix <- read.pcadapt(pcadapt_file, type = "pcadapt", type.out = "matrix") ``` -------------------------------- ### pcadapt() Source: https://context7.com/bcm-uga/pcadapt/llms.txt Performs principal component analysis on genetic data to identify population structure and compute test statistics for outlier detection. ```APIDOC ## pcadapt(input, K, pca.only, method) ### Description Performs PCA on genetic data. Can be used for PCA-only mode or to compute test statistics for genome scans. ### Parameters - **input** (object) - Required - The genetic data object (e.g., from read.pcadapt). - **K** (integer) - Optional - Number of principal components to retain. - **pca.only** (boolean) - Optional - If TRUE, returns only PCA results without computing statistics. - **method** (string) - Optional - Method for computing statistics (e.g., "componentwise"). ``` -------------------------------- ### Generate Score Plot with Population Labels Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Visualize population structure by projecting individuals onto principal components. Use the 'pop' argument to color individuals by their known population. ```R plot(x, option = "scores", pop = poplist.int) ``` ```R plot(x, option = "scores", pop = poplist.names) ``` -------------------------------- ### ped2pcadapt Function Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/ped2pcadapt.html Converts genetic data files from ped format to pcadapt format. ```APIDOC ## ped2pcadapt ### Description Converts ped files to the format pcadapt. ### Method Function Call ### Parameters #### Arguments - **input** (character string) - Required - The name of the file to be converted. - **output** (character string) - Required - The name of the output file. ### Request Example ped2pcadapt("input_file.ped", "output_file.pcadapt") ``` -------------------------------- ### Generate Manhattan Plot Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Generates a Manhattan plot to visualize p-values from the pcadapt analysis. Requires the 'pcadapt' object 'x'. ```R plot(x , option = "manhattan") ``` -------------------------------- ### Generate Q-Q Plot for P-values Source: https://context7.com/bcm-uga/pcadapt/llms.txt Assess the distribution of observed p-values against expected p-values using a Q-Q plot. This helps identify deviations from the null hypothesis. ```r # Q-Q plot - observed vs expected p-values plot(x, option = "qqplot") ``` -------------------------------- ### PCAdapt Object Structure Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html The 'x' object returned by the pcadapt function contains various numerical quantities derived from PCA on genotype data. These include scores, singular values, loadings, z-scores, allele frequencies, and statistics for outlier detection. ```APIDOC ## PCAdapt Object Structure The object `x` returned by the `pcadapt` function contains numerical quantities obtained after performing a PCA on the genotype matrix. We assume in the following that there are `n` individuals and `L` markers. * `scores`: A `(n,K)` matrix corresponding to the projections of the individuals onto each PC. * `singular.values`: A vector containing the `K` ordered square root of the proportion of variance explained by each PC. * `loadings`: A `(L,K)` matrix containing the correlations between each genetic marker and each PC. * `zscores`: A `(L,K)` matrix containing the z-scores. * `af`: A vector of size `L` containing allele frequencies of derived alleles where genotypes of `0` are supposed to code for homozygous for the reference allele. * `maf`: A vector of size `L` containing minor allele frequencies. * `chi2.stat`: A vector of size `L` containing the rescaled statistics `stat/gif` that follow a chi-squared distribution with `K` degrees of freedom. * `gif`: A numerical value corresponding to the genomic inflation factor estimated from `stat`. * `pvalues`: A vector containing `L` p-values. * `pass`: A list of SNPs indices that are kept after exclusion based on the minor allele frequency threshold. * `stat`: A vector of size `L` containing squared Mahalanobis distances by default. All of these elements are accessible using the `$` symbol. For example, the p-values are contained in `x$pvalues`. ``` -------------------------------- ### Convert BED to Matrix - pcadapt Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/bed2matrix.html Converts a BED file to an integer matrix. Ensure the BED file path is correct. The function can infer sample and SNP counts from associated .fam and .bim files if not provided. ```R bedfile <- system.file("extdata", "geno3pops.bed", package = "pcadapt") mat <- bed2matrix(bedfile) dim(mat) table(mat) ``` -------------------------------- ### Histogram of p-values Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Creates a histogram of p-values to visualize their distribution. Useful for identifying an excess of small p-values indicating outliers. Requires the 'pcadapt' object 'x'. ```R hist(x$pvalues, xlab = "p-values", main = NULL, breaks = 50, col = "orange") ``` -------------------------------- ### Outlier Detection Methods Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Methods for identifying outlier SNPs using q-values and the Benjamini-Hochberg procedure. ```APIDOC ## Choosing a Cutoff for Outlier Detection To provide a list of outliers and choose a cutoff for outlier detection, there are several methods that are listed below from the less conservative one to the more conservative one. ### q-values The `R` package [qvalue](http://www.bioconductor.org/packages/release/bioc/html/qvalue.html), transforms p-values into q-values. To install and load the package, type the following command lines: ```R ## try http if https is not available source("https://bioconductor.org/biocLite.R") biocLite("qvalue") library(qvalue) ``` For a given \alpha (real valued number between 0 and 1), SNPs with q-values less than \alpha will be considered as outliers with an expected false discovery rate bounded by \alpha. The false discovery rate is defined as the percentage of false discoveries among the list of candidate SNPs. Here is an example of how to provide a list of candidate SNPs for the **geno3pops** data, for an expected false discovery rate lower than `10%`: ```R library(qvalue) qval <- qvalue(x$pvalues)$qvalues alpha <- 0.1 outliers <- which(qval < alpha) length(outliers) ``` ### Benjamini-Hochberg Procedure ```R padj <- p.adjust(x$pvalues,method="BH") alpha <- 0.1 outliers <- which(padj < alpha) length(outliers) ``` ``` -------------------------------- ### Plot SNP Loadings for PCA Components Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Visualizes the loadings (contributions of each SNP to the principal components) for the first four PCs. Useful for identifying potential regions of Linkage Disequilibrium (LD). ```R par(mfrow = c(2, 2)) for (i in 1:4) plot(res$loadings[, i], pch = 19, cex = .3, ylab = paste0("Loadings PC", i)) ``` -------------------------------- ### Plot Distribution of Test Statistics Source: https://context7.com/bcm-uga/pcadapt/llms.txt Visualize the distribution of test statistics and compare it to the expected chi-squared distribution. This is useful for assessing the overall fit of the model. ```r # Histogram of test statistics with expected chi-squared distribution plot(x, option = "stat.distribution") ``` -------------------------------- ### get.pop.names Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/get.pop.names.html Retrieves population names from a list of population identifiers. ```APIDOC ## get.pop.names ### Description Retrieves the population names from the population file. ### Method Function Call ### Parameters #### Arguments - **pop** (list of integers or strings) - Required - A list specifying which population the individuals belong to. ### Request Example get.pop.names(pop = c(1, 1, 2, 2)) ``` -------------------------------- ### Generate Manhattan Plot for pcadapt Results Source: https://context7.com/bcm-uga/pcadapt/llms.txt Visualize p-values across the genome using a Manhattan plot. Chromosome information can be optionally provided. ```r # Manhattan plot (default) - displays -log10(p-values) for each SNP plot(x, option = "manhattan") # Manhattan plot with chromosome information # chr_info <- read.table("snp_positions.txt")$V1 # chromosome numbers # plot(x, option = "manhattan", chr.info = chr_info) ``` -------------------------------- ### Generate Interactive Plots with Plotly Source: https://context7.com/bcm-uga/pcadapt/llms.txt Create interactive versions of Manhattan and score plots using the plotly package. This allows for dynamic exploration of the results. ```r # Interactive plots using plotly plot(x, option = "manhattan", plt.pkg = "plotly") plot(x, option = "scores", pop = pop_labels, plt.pkg = "plotly") ``` -------------------------------- ### Perform PCA and Generate Scree Plot Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Performs Principal Component Analysis (PCA) on genotype data and generates a scree plot to help determine the optimal number of principal components (K). ```R res <- pcadapt(matrix, K = 20) plot(res, option = "screeplot") ``` -------------------------------- ### Identify Outliers using Benjamini-Hochberg Procedure Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Applies the Benjamini-Hochberg procedure to adjust p-values and identifies SNPs with adjusted p-values below a specified alpha threshold. Requires the 'pcadapt' object 'x'. ```R padj <- p.adjust(x$pvalues,method="BH") alpha <- 0.1 outliers <- which(padj < alpha) length(outliers) ``` -------------------------------- ### Convert vcfR genotype matrices to pcadapt format Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/vcf_convert.html Use this function to convert genotype matrices extracted from VCF files into the format required by pcadapt. ```R vcf_convert(string_geno, output, allele_sep) ``` -------------------------------- ### Perform PCA with LD Clumping Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/articles/pcadapt.html Performs PCA after applying SNP thinning based on Linkage Disequilibrium (LD) clumping parameters (window size and r2 threshold). This helps to mitigate the effect of LD on PCA. ```R res <- pcadapt(matrix, K = 20, LD.clumping = list(size = 200, thr = 0.1)) plot(res, option = "screeplot") ``` -------------------------------- ### Retrieve population names function signature Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/get.pop.names.html Basic function signature for retrieving population names from a list of integers or strings. ```R get.pop.names(pop) ``` -------------------------------- ### get.score.color Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/get.score.color.html Assigns colors to individuals based on their population for visualization purposes. ```APIDOC ## get.score.color ### Description Allows the user to display individuals of the same predefined population with the same color when using the option "scores" in pcadapt. ### Parameters #### Arguments - **pop** (list of integers or strings) - Required - A list specifying which population the individuals belong to. ### Request Example get.score.color(pop = c(1, 1, 2, 2, 3)) ``` -------------------------------- ### Generate Scree Plot for PCA Eigenvalues Source: https://context7.com/bcm-uga/pcadapt/llms.txt Visualize the proportion of variance explained by each principal component using a scree plot. You can specify the number of PCs to display. ```r # Scree plot - proportion of variance explained by each PC plot(x, option = "screeplot") plot(x, option = "screeplot", K = 10) # Show only first 10 PCs ``` -------------------------------- ### vcf_convert Function Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/vcf_convert.html Converts genotype matrices extracted from VCF files using vcfR to the format required by pcadapt. ```APIDOC ## vcf_convert ### Description `vcf_convert` converts outputs of `extract.gt` to the format `pcadapt`. ### Method R Function ### Endpoint N/A (R function) ### Parameters #### Arguments - **string_geno** (matrix) - Required - a genotype matrix extracted from a VCF file with `vcfR`. - **output** (character string) - Required - a character string indicating the name of the output file. - **allele_sep** (vector of characters) - Required - a vector of characters indicating what delimiters are used to separate alleles. ### Request Example ```R vcf_convert(string_geno = my_genotype_matrix, output = "output_file.geno", allele_sep = c("/")) ``` ### Response N/A (This function writes to a file and does not return a value in the typical API sense.) ``` -------------------------------- ### vcf2pcadapt Function Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/vcf2pcadapt.html The vcf2pcadapt function extracts genotype information from a VCF file and exports it in the format required by pcadapt. It utilizes the vcfR package for VCF file processing. Please note that this converter is not actively maintained, and the use of PLINK is recommended for new projects. ```APIDOC ## vcf2pcadapt ### Description Converts a VCF file to the pcadapt format using the vcfR package. ### Method Function call (R) ### Endpoint N/A (R function) ### Parameters #### Arguments - **input** (character string) - Required - The name of the VCF file to be converted. - **output** (character string) - Optional - The name of the output file. Defaults to "tmp.pcadapt". - **allele.sep** (vector of characters) - Optional - Delimiters used to separate alleles. Defaults to c("\/", "|"). ### Request Example ```R vcf2pcadapt(input = "my_genotypes.vcf", output = "my_pcadapt_data.txt", allele.sep = c("/")) ``` ### Response #### Success Response N/A (Function writes to a file) #### Response Example N/A ``` -------------------------------- ### Display a Manhattan plot with manhattan_plot Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/manhattan_plot.html Generates a Manhattan plot from a pcadapt object. Specify plt.pkg as 'plotly' for interactive plots or 'ggplot' for static ones. ```R manhattan_plot(x, chr.info, snp.info, plt.pkg = "ggplot", K = 1) ``` -------------------------------- ### Plot p-values Q-Q Plot Source: https://github.com/bcm-uga/pcadapt/blob/master/docs/reference/qq_plot.html Use `qq_plot` to visualize the distribution of computed p-values. Requires an output from the `outlier` function. The `K` argument specifies the principal component to display. ```R qq_plot(x, K = 1) ``` -------------------------------- ### LD Clumping Workflow in pcadapt Source: https://context7.com/bcm-uga/pcadapt/llms.txt Applies LD clumping to thin SNPs based on correlation thresholds before computing principal components. This helps mitigate spurious signals caused by linkage disequilibrium in dense SNP data. ```R library(pcadapt) # Load example data with LD structure path_to_file <- system.file("extdata", "SSMPG2017.rds", package = "pcadapt") genotypes <- readRDS(path_to_file) matrix_input <- read.pcadapt(genotypes, type = "pcadapt") # First, analyze without LD clumping to see the problem res_no_ld <- pcadapt(matrix_input, K = 20) plot(res_no_ld, option = "screeplot") # May suggest incorrect K # Check loadings for clustering (sign of LD artifacts) par(mfrow = c(2, 2)) for (i in 1:4) { plot(res_no_ld$loadings[, i], pch = 19, cex = 0.3, ylab = paste0("Loadings PC", i)) } # If loadings cluster in genomic regions, LD is affecting PCs # Apply LD clumping: size = window radius, thr = r^2 threshold res_ld <- pcadapt(matrix_input, K = 20, LD.clumping = list(size = 200, thr = 0.1)) plot(res_ld, option = "screeplot") # Now shows correct population structure # Run final analysis with optimal K and LD clumping res_final <- pcadapt(matrix_input, K = 2, LD.clumping = list(size = 200, thr = 0.1)) ```