### Install or Upgrade MethSCAn Source: https://github.com/anders-biostat/methscan/blob/master/docs/index.md Use the `--upgrade` flag to install the latest version of the MethSCAn package. The installation process is otherwise the same as a standard installation. ```bash python3 -m pip install --upgrade methscan ``` -------------------------------- ### Example Input File Format (Bismark .cov) Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md This example shows the first five lines of a CpG-specific .cov file generated by Bismark. The columns represent chromosome, start/end coordinates, methylation percentage, methylated reads, and unmethylated reads. ```plaintext 1 100021800 100021800 100.000000 1 0 1 100023064 100023064 0.000000 0 1 1 100026855 100026855 100.000000 1 0 1 100027218 100027218 100.000000 2 0 1 100051671 100051671 0.000000 0 2 ... ``` -------------------------------- ### Install or Upgrade Pip Source: https://github.com/anders-biostat/methscan/blob/master/docs/index.md Ensure you have a recent version of pip installed before proceeding with the MethSCAn installation. ```shell python3 -m pip install --upgrade pip ``` -------------------------------- ### Install MethSCAn Source: https://github.com/anders-biostat/methscan/blob/master/docs/index.md Install the MethSCAn package from the Python Package Index (PyPI). Dependencies are installed automatically. ```shell python3 -m pip install methscan ``` -------------------------------- ### Example VMR Output Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md A sample of the BED-like file output from `methscan scan`, showing chromosome, start, end, and methylation variance for discovered regions. ```text 2 3194798 3197978 0.07718534715010719 2 3379038 3381638 0.08048814475349723 2 4295158 4299148 0.06783578568141418 2 4443928 4446178 0.07310900984059789 2 4544208 4546518 0.08275669639137119 ... ``` -------------------------------- ### Install MethSCAn with Pipx Source: https://github.com/anders-biostat/methscan/blob/master/docs/index.md Use pipx for installing MethSCAn on newer Ubuntu versions to manage virtual environments. Restart your terminal after installation. ```bash pipx install methscan ``` -------------------------------- ### Add Local Bin to PATH Source: https://github.com/anders-biostat/methscan/blob/master/docs/index.md If the 'methscan' script is not found, add its installation directory to your system's PATH. Alternatively, copy the script to a directory already in your PATH. ```bash WARNING: The script methscan is installed in '/home/ubuntu/.local/bin' which is not on PATH. ``` ```bash cp /home/ubuntu/.local/bin/methscan /usr/local/bin ``` -------------------------------- ### Check MethSCAn Version Source: https://github.com/anders-biostat/methscan/blob/master/docs/index.md Verify that the latest version of MethSCAn has been correctly installed by checking its version number. ```bash methscan --version ``` -------------------------------- ### Example Methylation Matrix (Tabular) Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md A preview of the cell x region methylation matrix, showing average methylation values for VMRs in different cells. Note the presence of missing values and fractional measurements characteristic of single-cell data. ```text | | 1:7844602-7846612 | 1:8409032-8412852 | 1:10376412-10378562 | ... | |---------|-------------------|-------------------|---------------------|-----| | cell_01 | | 1.0 | | | | cell_02 | | 1.0 | 0.6666667 | | | cell_03 | | 0.0 | 1.0 | | | cell_04 | 1.0 | 0.3333333 | 0.0 | | | ... | | | | | ``` -------------------------------- ### Profile Methylation Around TSS with MethSCAn Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Generate average methylation profiles around transcription start sites (TSSs) using 'methscan profile'. This helps identify cells with unusual methylation patterns, which may indicate low quality. Specify the strand column if necessary. ```bash methscan profile --strand-column 6 scbs_tutorial_data/Mus_musculus.GRCm38.102_TSS.bed compact_data TSS_profile.csv ``` -------------------------------- ### Display MethSCAn Help Source: https://github.com/anders-biostat/methscan/blob/master/docs/index.md Access the help documentation for MethSCAn to understand its commands and usage. ```bash methscan --help ``` -------------------------------- ### Displaying MethSCAn Help Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md View available MethSCAn commands by running `methscan --help` or `methscan` in the terminal. Use `methscan [command] --help` for command-specific arguments. ```bash methscan --help ``` ```bash methscan ``` ```bash methscan prepare --help ``` -------------------------------- ### MethScan CLI Usage Source: https://github.com/anders-biostat/methscan/blob/master/docs/commands.md Displays the general usage instructions for the MethScan command-line interface, including available options and commands. ```bash Usage: methscan [OPTIONS] COMMAND [ARGS]... __ __ _ _ ____ ____ _ | \/ | ___| |_| |__ / ___| / ___| / \ _ __ | |\/| |/ _ \ __| '_ \\___ \| | / _ \ | '_ \ | | | | __/ |_| | | |___) | |___ / ___ \| | | | |_| |_|\___|\__|_| |_|____/ \____/_/ \_\_| |_| v1.0.2 Below you find a list of all available commands. To find out what they do and how to use them, check their help like this: methscan [command] --help For documentation and a usage tutorial, go to https://anders-biostat.github.io/MethSCAn/. Options: --version Show the version and exit. --cite Show publication reference and exit. --help Show this message and exit. Commands: prepare Collect and store sc-methylation data for quick access filter Filter low-quality cells based on coverage and mean methylation smooth Smooth the pseudobulk of single cell methylation data scan Scan the genome to discover variably methylated regions diff Discover differentially methylated regions between groups of cells matrix Make a methylation matrix, similar to a count matrix in scRNA-seq profile Plot mean methylation around a group of genomic features ``` -------------------------------- ### MethScan Prepare Command Usage Source: https://github.com/anders-biostat/methscan/blob/master/docs/commands.md Details the usage of the 'prepare' command, which gathers and stores single-cell methylation data. It specifies input file formats and output directory requirements. ```bash Usage: methscan prepare [OPTIONS] [INPUT_FILES]... DATA_DIR Gathers single cell methylation data from multiple input files (one per cell) and creates a sparse matrix (position x cell) in CSR format for each chromosome. Methylated sites are represented by a 1, unmethylated sites are -1, missing values and other bases are 0. INPUT_FILES are single cell methylation files, for example '.cov'-files generated by Bismark. DATA_DIR is the output directory where the methylation data will be stored. Note: If you have many cells and encounter a "too many open files"- error, you need to increase the open file limit with e.g. 'ulimit -n 99999'. Options: --round-sites Specify that you want to round methylation sites with ambigous status to 0% or 100%. This means, for example, that a CpG site with 5 methylated reads and 1 unmethylated read will be considered methylated in that cell. Otherwise, ambiguous sites will be discarded. Note that sites with the same number of methylated and unmethylated reads will always be discarded. --chunksize INTEGER The data of each chromosome is read in chunks [default: 10 Mbp] to reduce memory requirements. If you are running out of RAM, decrease the chunk size (in bp). [x>=1] --input-format TEXT Specify the format of the input files. Options: 'bismark' (default), 'methylpy', 'allc', 'biscuit', 'biscuit_short' or custom (see below). You can specify a custom format by specifying the separator, whether the file has a header, and which information is stored in which columns. These values should be separated by ':' and enclosed by quotation marks, for example --input-format '1:2:3:4u:\t:1' The six ':'-separated values denote the number of the columns that contain 1. the chromosome name 2. the genomic position 3. the methylated counts 4. either the total coverage (c) or the number of unmethylated counts (u), followed by either 'c' or 'u', e.g. '4c' to denote that the 4th column contains the coverage 5. The separator, e.g. '\t' or 'TAB' for tsv files or ',' for csv 6. Either '1' if the file has a header or '0' if it does not have a header All column numbers are 1-indexed, i.e. to define the first column use '1' and not '0'. --help Show this message and exit. ``` -------------------------------- ### Prepare Methylation Data with MethSCAn Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Use 'methscan prepare' to collect and efficiently store methylation data from raw single-cell files. This is the initial step and requires raw data; subsequent commands use the generated 'compact_data'. Increase open file limits if encountering 'too many open files' errors. ```bash methscan prepare scbs_tutorial_data/*.cov compact_data ``` -------------------------------- ### Increase Open File Limit Source: https://github.com/anders-biostat/methscan/blob/master/docs/index.md If encountering 'too many open files' errors during 'methscan prepare', increase the maximum number of open files using the ulimit command. ```bash ulimit -n 99999 ``` -------------------------------- ### Perform UMAP on PCA Results in R Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Applies the UMAP algorithm to the principal components obtained from PCA. Requires the 'uwot' package. Adjust 'n_neighbors' and 'min_dist' for different visualizations. ```r library(uwot) # R package for UMAP umap_obj <- uwot::umap(pca$x, min_dist=0.05, n_neighbors=5, seed=2, ret_nn=T) umap_tbl <- umap_obj$embedding %>% magrittr::set_colnames(c("UMAP1", "UMAP2")) %>% as_tibble() %>% add_column(cell=rownames(meth_mtx)) umap_tbl %>% ggplot(aes(x = UMAP1, y = UMAP2)) + geom_point() + coord_fixed() + labs(title="UMAP based on VMR methylation") ``` -------------------------------- ### MethScan diff Command Usage Source: https://github.com/anders-biostat/methscan/blob/master/docs/commands.md This snippet shows the general usage and available options for the 'methscan diff' command. It outlines the required arguments and various flags to customize the DMR scanning process. ```bash Usage: methscan diff [OPTIONS] DATA_DIR CELL_GROUPS OUTPUT Scans the whole genome for differentially methylated regions (DMRs) between two groups of cells. This works by sliding a window across the genome, performing a t-test for each window, and merging windows above a threshold. To control the false discovery rate, the same procedure is repeated on permutations of the data which are then used to calculate an adjusted p-value for each DMR. DATA_DIR is the directory containing the methylation matrices produced by running 'methscan prepare', as well as the smoothed methylation values produced by running 'methscan smooth'. CELL_GROUPS is a comma-separated text file that lists the group membership (e.g. cell type or treatment) of each cell. Each row contains two comma-separated values: The cell name and its group label. Cell names are denoted in DATA_DIR/column_header.txt. Only two cell groups can be compared, so there should only be two unique group labels (e.g. "neuron" and "glia" or "wildtype" and "KO"). To exclude cells that do not belong to either group from the analysis, you can assign them the group label '-' (dash character). OUTPUT is the path of the output file in '.bed' format, containing the DMR genome coordinates, their t-statistic, the cell group in which the DMR has lower methylation, and the adjusted p-value. Options: -bw, --bandwidth INTEGER Bandwidth of the sliding window in basepairs. Increase this value to find larger DMRs. [default: 2000; x>=1] --stepsize INTEGER Step size of the sliding window in basepairs. Increase this value to gain speed, at the cost of some accuracy. [default: 1000; x>=1] --threshold FLOAT The t-statistic threshold, i.e. 0.02 means that the top 2% and bottom 2% most differentially methylated genomic bins will be separately merged and reported as DMRs with adjusted p-values. [default: 0.02; 0<=x<=1] --min-cells INTEGER The minimum number of cells required to consider a genomic region for testing. For example, a value of 6 means that only regions with sequencing coverage in at least 6 cells per group are considered. [default: 6; x>=1] --bridge-gaps INTEGER Merge neighboring DMRs if they are within this distance in basepairs. Useful to prevent fragmented DMRs separated only by small gaps. [default: off] [x>=0] --threads INTEGER How many CPU threads to use in parallel. [default: all available] --write-header Write the column names of the output file. [default: off] --debug Use this to also report DMRs that were identified in permutations. [default: off] --help Show this message and exit. ``` -------------------------------- ### Visualize Cell Quality Metrics with R Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Visualize cell quality metrics such as global methylation percentage and the number of observed CpG sites using R and ggplot2. This helps identify outlier cells with low site counts or unusual methylation levels. ```r library(tidyverse) cell_stats <- read_csv("compact_data/cell_stats.csv") cell_stats %>% ggplot(aes(x = global_meth_frac * 100, y = n_obs)) + geom_point() + labs(x = "global DNA methylation %", y = "# of observed CpG sites") ``` -------------------------------- ### Use stdin and stdout with MethScan Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Redirect output from one tool to MethScan's input using the '-' character. This is useful for chaining commands, like sorting with bedtools before processing with methscan matrix. ```bash bedtools sort -i unsorted.bed > sorted.bed methscan matrix sorted.bed filtered_data output ``` ```bash bedtools sort -i unsorted.bed | methscan matrix - filtered_data output ``` -------------------------------- ### Load Methylation Matrix in R Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Reads a CSV.GZ file containing methylation data into an R matrix. Ensure the file path is correct. ```r library(tidyverse) library(irlba) meth_mtx <- read.csv("VMR_matrix/mean_shrunken_residuals.csv.gz", row.names=1) %>% as.matrix() ``` -------------------------------- ### MethScan Smooth Command Usage Source: https://github.com/anders-biostat/methscan/blob/master/docs/commands.md Calculates smoothed mean methylation over the whole genome. DATA_DIR is the directory containing methylation matrices. Output is written to DATA_DIR/smoothed/. ```bash Usage: methscan smooth [OPTIONS] DATA_DIR This script will calculate the smoothed mean methylation over the whole genome. DATA_DIR is the directory containing the methylation matrices produced by running 'methscan prepare'. The smoothed methylation values will be written to DATA_DIR/smoothed/. Options: -bw, --bandwidth INTEGER Smoothing bandwidth in basepairs. [default: 1000; x>=1] --use-weights Use this to weigh each methylation site by log1p(coverage). [default: off] --help Show this message and exit. ``` -------------------------------- ### Generate Methylation Matrix for Specific Features Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Quantifies methylation for a specified set of genomic features, such as promoters, across all cells. Useful for targeted methylation analysis. ```bash methscan matrix --threads 4 scbs_tutorial_data/mouse_promoters.bed filtered_data promoter_matrix ``` -------------------------------- ### Filter cells by name using a whitelist Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Specify a file containing cell names to keep. MethScan will only process data from the cells listed in the provided file. ```bash methscan filter --cell-names cells_to_keep.txt --keep compact_data filtered_data ``` -------------------------------- ### Generate Methylation Matrix from VMRs Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Quantifies the mean methylation of discovered VMRs across all cells. Outputs a cell x region methylation matrix. ```bash methscan matrix --threads 4 VMRs.bed filtered_data VMR_matrix ``` -------------------------------- ### Smooth Methylation Data Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Smooths methylation data to create a pseudo-bulk sample for genome-wide analysis. This is a prerequisite for VMR detection. ```bash methscan smooth filtered_data ``` -------------------------------- ### MethScan Scan Command Usage Source: https://github.com/anders-biostat/methscan/blob/master/docs/commands.md Scans the whole genome for variably methylated regions (VMRs) by sliding a window across the genome. DATA_DIR contains methylation matrices and smoothed values. OUTPUT is the path for the .bed output file. ```bash Usage: methscan scan [OPTIONS] DATA_DIR OUTPUT Scans the whole genome for variably methylated regions (VMRs). This works by sliding a window across the genome, calculating the variance of methylation per window, and selecting windows above a variance threshold. DATA_DIR is the directory containing the methylation matrices produced by running 'methscan prepare', as well as the smoothed methylation values produced by running 'methscan smooth'. OUTPUT is the path of the output file in '.bed' format, containing the VMRs that were found. Options: -bw, --bandwidth INTEGER Bandwidth of the sliding window in basepairs. Increase this value to find larger VMRs. [default: 2000; x>=1] --stepsize INTEGER Step size of the sliding window in basepairs. Should be smaller than the bandwidth. Increase this value to gain speed, at the cost of some accuracy. [default: 100; x>=1] --var-threshold FLOAT The variance threshold, i.e. 0.02 means that the top 2% most variable genomic bins will be merged and reported as VMRs. [default: 0.02; 0<=x<=1] --min-cells INTEGER The minimum number of cells required to report a VMR. For example, a value of 6 means that only VMRs with sequencing coverage in at least 6 cells are reported. [default: 6; x>=1] --bridge-gaps INTEGER Merge neighboring VMRs if they are within this distance in basepairs. Useful to prevent fragmented VMRs separated only by small gaps. [default: off] [x>=0] --threads INTEGER How many CPU threads to use in parallel. [default: all available] --write-header Write the column names of the output file. [default: off] --help Show this message and exit. ``` -------------------------------- ### Filter cells by name using a blacklist Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Specify a file containing cell names to discard. MethScan will exclude data from the cells listed in the provided file. ```bash methscan filter --cell-names cells_to_discard.txt --discard compact_data filtered_data ``` -------------------------------- ### Load Methylation Matrix with data.table::fread Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md This R code demonstrates using `fread` from the `data.table` package for faster loading of large CSV files, specifically a methylation matrix. It converts the loaded data into a matrix format. ```r meth_mtx <- "VMR_matrix/mean_shrunken_residuals.csv.gz" %>% data.table::fread(sep=",") %>% as.matrix(rownames=1) ``` -------------------------------- ### Filter Low-Quality Cells Source: https://github.com/anders-biostat/methscan/blob/master/docs/commands.md Use this command to filter cells based on minimum/maximum methylation sites or global methylation percentage. Ensure DATA_DIR contains prepared methylation matrices and FILTERED_DIR is the output location. ```bash Usage: methscan filter [OPTIONS] DATA_DIR FILTERED_DIR Filters low-quality cells based on the number of observed methylation sites and/or the global methylation percentage. Alternatively, you may also provide a text file with the names of the cells you want to keep. DATA_DIR is the unfiltered directory containing the methylation matrices produced by running 'methscan prepare'. FILTERED_DIR is the output directory storing methylation data only for the cells that passed all filtering criteria. Options: --min-sites INTEGER Minimum number of methylation sites required for a cell to pass filtering. [x>=1] --max-sites INTEGER Maximum number of methylation sites required for a cell to pass filtering. [x>=1] --min-meth PERCENT Minimum average methylation percentage required for a cell to pass filtering. [0<=x<=100] --max-meth PERCENT Maximum average methylation percentage required for a cell to pass filtering. [0<=x<=100] --cell-names FILENAME A text file with the names of the cells you want to keep (default) or remove. This is an alternative to the min/max filtering options. Each cell name must be on a new line. --keep / --discard Specify whether the cells listed in your text file should be kept (default) or discarded from the data set. Only use together with --cell-names. --help Show this message and exit. ``` -------------------------------- ### Discover Variably Methylated Regions (VMRs) Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Detects variably methylated regions in the smoothed methylation data. Supports parallel processing using the --threads option. ```bash methscan scan --threads 4 filtered_data VMRs.bed ``` -------------------------------- ### Run Leiden Clustering on UMAP Neighbor Graph Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md This R code performs Leiden clustering on a neighbor graph obtained from UMAP. It requires the 'igraph' package. Adjust the resolution parameter for different clustering granularities. ```r library(igraph) # R package for graph manipulation, also implements the Leiden algorithm # get the edges of the neighbor graph from the UMAP object neighbor_graph_edges <- tibble(from = rep(1:nrow(umap_obj$nn$euclidean$idx), times=ncol(umap_obj$nn$euclidean$idx)), to = as.vector(umap_obj$nn$euclidean$idx), weight = as.vector(umap_obj$nn$euclidean$dist)) %>% filter(from != to) %>% mutate(from = rownames(meth_mtx)[from], to = rownames(meth_mtx)[to]) # run Leiden clustering clust_obj <- neighbor_graph_edges %>% igraph::graph_from_data_frame(directed=F) %>% igraph::cluster_leiden(resolution_parameter = .5) # adjust the resolution parameter to your needs # put the clustering results into a data frame (tibble) for plotting clust_tbl <- tibble( leiden_cluster = as.character(clust_obj$membership), cell = clust_obj$names ) %>% full_join(umap_tbl, by="cell") clust_tbl %>% ggplot(aes(x = UMAP1, y = UMAP2, color = leiden_cluster)) + geom_point() + coord_fixed() ``` -------------------------------- ### Analyze TSS Methylation Profiles with R Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Analyze and visualize average methylation profiles around TSSs using R. This involves reading the profile data, binning positions, calculating mean methylation fractions, and plotting the results per cell. ```r library(tidyverse) profile_df <- read_csv("TSS_profile.csv") %>% mutate(position_binned = round(position, -1L)) %>% group_by(position_binned, cell_name) %>% summarise(meth_frac = mean(meth_frac)) %>% ungroup() profile_df %>% ggplot(aes(x = position_binned / 1000, y = meth_frac)) + scale_y_continuous(labels=scales::percent_format(accuracy=1), limits=c(0, 1), breaks=c(0, .5, 1)) + geom_line(size=.1) + facet_wrap(~cell_name) + labs(x = "position relative to TSS [kb]", y = "DNA methylation") ``` -------------------------------- ### Perform and Plot PCA in R Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Applies the iterative PCA function to a scaled methylation matrix and visualizes the results using ggplot2. Adjust 'n' for more principal components. ```r pca <- meth_mtx %>% scale(center = T, scale = F) %>% prcomp_iterative(n = 5) # increase this value to e.g. 15 for real data sets pca_tbl <- as_tibble(pca$x) %>% add_column(cell=rownames(meth_mtx)) pca_tbl %>% ggplot(aes(x = PC1, y = PC2)) + geom_point() + coord_fixed() + labs(title="PCA based on VMR methylation") ``` -------------------------------- ### Create Cell Group CSV for MethScan Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md This R code generates a CSV file mapping cells to specified groups (group_A, group_B, or '-') for use with the `methscan diff` command. It uses `write_csv` from the `readr` package. ```r clust_tbl %>% mutate(cell_group = case_when( leiden_cluster == "1" ~ "-", leiden_cluster == "2" ~ "group_A", leiden_cluster == "3" ~ "group_B")) %>% dplyr::select(cell, cell_group) %>% write_csv("cell_groups.csv", col_names=F) ``` -------------------------------- ### Filter Low-Quality Cells with MethSCAn Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md Filter low-quality cells from the methylation data using 'methscan filter'. Specify minimum and maximum thresholds for observed methylation sites and global methylation percentage. Alternatively, cells can be selected by name for finer control. ```bash methscan filter --min-sites 60000 --min-meth 20 --max-meth 60 compact_data filtered_data ``` -------------------------------- ### Run MethScan Differential Methylation Analysis Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md This bash command executes MethScan to find differentially methylated regions (DMRs) between two specified cell groups. It utilizes a cell group definition file and outputs results to a BED file. ```bash methscan diff --threads 4 filtered_data cell_groups.csv DMRs.bed ``` -------------------------------- ### Iterative PCA for Missing Value Imputation in R Source: https://github.com/anders-biostat/methscan/blob/master/docs/tutorial.md An R function to perform Principal Component Analysis (PCA) with iterative imputation of missing values. It replaces NAs with zeros, runs PCA, imputes NAs with PCA predictions, and repeats until convergence or max iterations. Useful for methylation matrices with missing data. ```r # PCA that iteratively imputes missing values prcomp_iterative <- function(x, n=10, n_iter=50, min_gain=0.001, ...) { mse <- rep(NA, n_iter) na_loc <- is.na(x) x[na_loc] = 0 # zero is our first guess for (i in 1:n_iter) { prev_imp <- x[na_loc] # what we imputed in the previous round # PCA on the imputed matrix pr <- prcomp_irlba(x, center = F, scale. = F, n = n, ...) # impute missing values with PCA new_imp <- (pr$x %*% t(pr$rotation))[na_loc] x[na_loc] <- new_imp # compare our new imputed values to the ones from the previous round mse[i] = mean((prev_imp - new_imp) ^ 2) # if the values didn't change a lot, terminate the iteration gain <- mse[i] / max(mse, na.rm = T) if (gain < min_gain) { message(paste(c("\n\nTerminated after ", i, " iterations."))) break } } pr$mse_iter <- mse[1:i] pr } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.