Package {slideimp}


Type: Package
Title: Numeric Matrices K-NN and PCA Imputation
Version: 1.3.0
Description: Fast k-nearest neighbor (K-NN) and principal component analysis (PCA) imputation of missing values in high-dimensional numeric matrices, such as DNA methylation data. PCA imputation can use a locally optimal block preconditioned conjugate gradient (LOBPCG) eigensolver, which warm-starts each iteration from the previous eigenblock and search direction. Group-wise imputation, for example by chromosome, is recommended for Illumina DNA methylation arrays such as 450K and EPIC, and for other matrices with groupable columns. Sliding-window imputation imputes columns ordered by position. Tuning functions choose hyperparameters by masking observed values, imputing them, and scoring the result over repeated random masks. The Bayesian PCA sampler draws multiple imputations of the missing values. For whole-genome methylation data, such as whole-genome bisulfite sequencing (WGBS) or Enzymatic Methyl-seq (EM-seq), the sampler is recommended because such data are sparsely observed. The K-NN method is described in Troyanskaya et al. (2001) <doi:10.1093/bioinformatics/17.6.520>. PCA imputation is an optimized reimplementation of imputePCA() from the 'missMDA' package, described in Josse and Husson (2016) <doi:10.18637/jss.v070.i01>. The sampler implements the Bayesian method of MIPCA() in 'missMDA', described in Audigier, Husson and Josse (2016) <doi:10.1080/00949655.2015.1104683>.
License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]
URL: https://github.com/hhp94/slideimp, https://hhp94.github.io/slideimp/
BugReports: https://github.com/hhp94/slideimp/issues
Depends: R (≥ 4.4.0)
Imports: checkmate, cli, collapse, dqrng (≥ 0.4.1), mirai (≥ 2.5.0), Rcpp, RhpcBLASctl, rlang, stats, utils
Suggests: knitr, missMDA, quarto, rcpptimer, rmarkdown, testthat (≥ 3.2.3), withr
LinkingTo: BH, dqrng (≥ 0.4.1), Rcpp, RcppEigen, RcppThread
VignetteBuilder: knitr, quarto
Config/Needs/website: rmarkdown
Config/roxygen2/version: 8.1.1
Config/testthat/edition: 3
Encoding: UTF-8
Language: en-US
NeedsCompilation: yes
Packaged: 2026-11-23 05:14:04 UTC; amser
Author: Hung Pham ORCID iD [aut, cre, cph], Francois Husson ORCID iD [ctb, cph] ('missMDA' imputePCA() and MIPCA(), reimplemented in R/pca_imp.R, src/pca_kernel.cpp, R/mi_pca_imp.R and src/mipca.cpp), Julie Josse ORCID iD [ctb, cph] ('missMDA' imputePCA() and MIPCA(), reimplemented in R/pca_imp.R, src/pca_kernel.cpp, R/mi_pca_imp.R and src/mipca.cpp), Vincent Audigier [ctb, cph] ('missMDA' MIPCA() Bayesian sampler, reimplemented in R/mi_pca_imp.R and src/mipca.cpp), Posit Software, PBC [cph] ('carrier' package code, adapted in R/crate.R and tests/testthat/test-crate*.R), Yixuan Qiu [ctb, cph] (Spectra library, vendored in src/Spectra), Gael Guennebaud [ctb, cph] (Eigen SelfAdjointEigenSolver code, adapted in src/Spectra/LinAlg/TridiagEigen.h), Jitse Niesen [ctb, cph] (Eigen SelfAdjointEigenSolver code, adapted in src/Spectra/LinAlg/TridiagEigen.h)
Maintainer: Hung Pham <amser.hoanghung@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-23 07:50:02 UTC

slideimp: Numeric Matrices K-NN and PCA Imputation

Description

Provides K-nearest-neighbor, PCA, grouped, and sliding-window imputation methods for numeric matrices, along with utilities for simulation and parameter tuning.

Column mean fill

A column with a proportion of missing values greater than colmax takes no part in the imputation. The method neither uses the column to impute other columns nor imputes it.

With post_imp = TRUE, column means replace the missing values that remain after the method has run. Two kinds of missing value can remain: the missing values of the columns that took no part, and the cells for which the method found no value. Each column mean is the mean of the column's observed values. With post_imp = FALSE, both kinds stay missing.

The result records what the column means replaced, in two attributes:

Both attributes are empty when no column mean was used. print() reports them when they are not empty.

Missing values and non-finite input

obj must be a double matrix. An integer or logical matrix is rejected, not converted. Convert one with storage.mode(obj) <- "double".

NA and NaN are both treated as missing. The package does not distinguish between them.

Inf and -Inf are rejected on entry, and so is a column with no observed values (every cell NA or NaN). Locate them with which(is.infinite(obj), arr.ind = TRUE) and which(colSums(!is.na(obj)) == 0).

Author(s)

Maintainer: Hung Pham amser.hoanghung@gmail.com (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


Propose Columns to Draw by Approximate Bayesian Bootstrap

Description

Find the columns of a matrix of proportions, such as DNAm beta values, whose observed values lie almost all near 0 or almost all near 1. Pass the result as abb to mipca(), mipca_tune() or mipca_flank_plan().

Usage

abb_cols(obj, bound = 0.02, q = 0.95)

Arguments

obj

A double matrix with samples in rows and features in columns. Row and column names are required and must be unique. Every observed value must lie in ⁠[0, 1]⁠.

bound

Numeric. A value below bound counts as near 0, and a value above 1 - bound as near 1. Must be above 0 and below 0.5. Defaults to 0.02.

q

Numeric. Proportion of a column's observed values that must be near 0, or near 1, for the column to be listed. Must be above 0.5 and at most 1. Defaults to 0.95.

Details

The listed columns. A column listed in abb is left out of the model, and its missing values are drawn from its own observed values by approximate Bayesian bootstrap (Rubin and Schenker 1986). Unlike the model, this keeps the exact 0s and 1s such columns often hold. Each column is drawn on its own, so its relation to the other columns is not kept. mipca_tune() tunes on the other columns, and summary() does not report the listed ones.

Choosing the list. The defaults list only the most extreme columns. Raise bound or lower q to list more, or pass any columns to abb. A column with no observed values is never listed.

Value

An integer vector of column numbers in obj, in increasing order. It is empty when no column is listed, and abb takes it as no list.

References

Rubin DB, Schenker N (1986). Multiple imputation for interval estimation from simple random samples with ignorable nonresponse. Journal of the American Statistical Association, 81(394), 366-374. doi:10.1080/01621459.1986.10478280

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)
obj <- sim$input

# Push two columns against 0 and 1
obj[, 3] <- obj[, 3] / 100
obj[, 4] <- 1 - (1 - obj[, 4]) / 100

abb <- abb_cols(obj)
abb

fit <- mipca(obj, rank = 2, transform = "logit_biwhiten", seed = 1, abb = abb)
fit

Completed Matrix from a Bayesian PCA Imputation

Description

Fill the missing values of obj with one draw from a finalized fit.

Usage

## S3 method for class 'si_mi'
x[...]

## S3 method for class 'si_mi'
as.matrix(x, draw = 1L, ...)

## S3 method for class 'si_mi_pca'
as.matrix(x, ...)

Arguments

x

A si_mi object. A finalized fit, from mipca(), mipca_fit() or mipca_finalize().

...

Not used.

draw

Integer. The kept draw that fills the missing values, from 1 to the number of kept draws. Defaults to 1.

Details

The completed matrix. A completed matrix is obj with its missing values filled by one draw, on the scale of obj. The observed values are unchanged, and the row and column names are kept. A fit made with subset gives a matrix of the selected columns only.

Which draws. print() shows the number of kept draws. They are numbered chain by chain: with k draws per chain, draws 1 to k are the first chain's, k + 1 to 2 * k the second's, and so on.

Multiple imputation. Call as.matrix() once per draw. Draws evenly spaced from the first to the last are spread across the chains. Each completed matrix is a full copy of obj, so m of them take m times its memory. On a large obj, use each matrix in turn instead of keeping all of them.

Refusals. A resumable fit, made with keep_state = TRUE, is refused. Finalize it with mipca_finalize() first. [ does not work on a finalized fit: choose the columns with subset when fitting, or subset a completed matrix.

Value

A numeric matrix.

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)
fit <- mipca(sim$input, rank = 2, transform = "logit_biwhiten", seed = 1)
fit

# The matrix completed by draw 10
x10 <- as.matrix(fit, draw = 10)

# Five completed matrices, at draws spread over the 400 kept
b <- round(seq(1, 400, length.out = 5))
completed <- lapply(b, function(d) as.matrix(fit, draw = d))

Join Bayesian PCA Imputations of Different Columns

Description

Join finalized fits made on the same rows over different columns into one fit, such as a large matrix fitted one chromosome at a time.

Usage

## S3 method for class 'si_mi'
cbind(..., deparse.level = 1)

Arguments

...

One or more si_mi objects. Finalized fits, from mipca(), mipca_fit() or mipca_finalize().

deparse.level

Not used.

Details

The joined fit. The columns come in the order the fits are given. Draw b of the joined fit is draw b of every fit, so its completed matrix is the completed matrices of the fits at draw b, side by side.

What must match. The fits must have the same row names in the same order and the same number of kept draws, so fit and finalize each with the same chains, iter_sampling and thin. A column can be in one fit only. The rank, transform and other settings can differ.

Seeds. Give each fit its own seed, to reduce the correlation between the draws of different fits.

Refusals. A resumable fit, made with keep_state = TRUE, is refused. Finalize it with mipca_finalize() first.

Value

A finalized fit of class si_mi, over the columns of every fit. A single fit is returned as it is.

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 40, beta = TRUE)
obj <- sim$input

# Fit two blocks of columns, each with its own seed, and join them
left <- mipca(obj[, 1:20], rank = 2, transform = "logit_biwhiten", seed = 1)
right <- mipca(obj[, 21:40], rank = 2, transform = "logit_biwhiten", seed = 2)
fit <- cbind(left, right)
fit
dim(as.matrix(fit, draw = 1))

Matrix Column Variances

Description

Compute the sample variance for each column of a numeric matrix.

Usage

col_vars(obj)

Arguments

obj

A double matrix.

Details

NA and NaN are treated as missing and dropped, as stats::var() does with na.rm = TRUE. A column with fewer than two non-missing values has variance NA.

Inf and -Inf are not missing. A column that contains one and has at least two non-missing values has variance NaN, as in base R.

Value

A numeric vector of column variances, named if obj has column names.

Examples

set.seed(123)
obj <- matrix(rnorm(7 * 10), ncol = 7)
obj[1, 1] <- Inf
obj[1, 2] <- NA
obj[1:8, 3] <- NA
obj[8, 3] <- Inf
obj[1:8, 4] <- NA
obj[1:8, 5] <- NA
obj[9, 5] <- obj[10, 5]
obj[1:9, 6] <- NA
obj[, 7] <- NA
obj

col_vars(obj)
apply(obj, 2, var, na.rm = TRUE)

Compute Prediction Accuracy Metrics

Description

Computes accuracy metrics for each parameter set and repetition in the output of tune_imp().

Usage

compute_metrics(results, metrics = c("mae", "rmse"))

## S3 method for class 'data.frame'
compute_metrics(results, metrics = c("mae", "rmse"))

## S3 method for class 'slideimp_tune'
compute_metrics(results, metrics = c("mae", "rmse"))

Arguments

results

A slideimp_tune object or a data frame. The output of tune_imp(), or a data frame whose result list-column holds data frames with truth and estimate columns.

metrics

Character. The metrics to compute, any of "mae", "rmse", "mape", "bias", "rsq", and "rsq_trad". Defaults to c("mae", "rmse").

Details

Each metric is taken over the masked values of one row of results. A masked value with no estimate is left out, and n_miss counts it.

Value

A data frame with one row per row of results and metric. It keeps every column of results except result, and adds n, the number of masked values, n_miss, the number of those with no estimate, .metric, .estimator, and .estimate.

Examples

set.seed(1234)
obj <- sim_mat(20, 30)$input

results <- tune_imp(
  obj = obj,
  parameters = data.frame(k = 5),
  .f = "knn_imp",
  n_reps = 1,
  num_na = 10,
  .progress = FALSE
)

compute_metrics(results)


Grouped K-NN or PCA Imputation

Description

Perform K-NN or PCA imputation independently within feature groups.

Usage

group_imp(
  obj,
  group,
  subset = NULL,
  allow_unmapped = FALSE,
  k = NULL,
  ncp = NULL,
  method = NULL,
  cores = 1,
  .progress = TRUE,
  min_group_size = NULL,
  colmax = NULL,
  post_imp = NULL,
  dist_pow = NULL,
  scale = NULL,
  coeff.ridge = NULL,
  threshold = NULL,
  row.w = NULL,
  seed = NULL,
  nb.init = NULL,
  maxiter = NULL,
  miniter = NULL,
  solver = NULL,
  lobpcg_control = NULL,
  clamp = NULL,
  pin_blas = TRUE,
  on_infeasible = c("error", "skip", "mean")
)

Arguments

obj

A double matrix. Samples are in rows and features in columns.

group

A data frame or a character scalar. The feature groups, in one of these forms:

  • A character scalar naming a supported Illumina platform, such as "EPICv2". This needs the slideimp.extra package.

  • A long-format data frame with columns group and feature.

  • A list-column data frame with a feature list-column. Optional list-columns are aux, for auxiliary feature names, and parameters, for group-specific parameter lists.

subset

Optional character vector. The features to impute and return, by name, or NULL to impute every grouped feature and return every column. A group's other features become its auxiliary columns, and a group left with no feature is dropped with a message.

allow_unmapped

Logical. If FALSE, every column in colnames(obj) must appear in group. If TRUE, columns with no group assignment are left untouched and are not used as auxiliary columns.

k

Integer or NULL. Number of nearest neighbors for K-NN imputation. If NULL, k may be supplied through group$parameters.

ncp

Integer or NULL. Number of components for PCA imputation. If NULL, ncp may be supplied through group$parameters.

method

Character or NULL. One of "euclidean" or "manhattan" for K-NN imputation, or "regularized" or "EM" for PCA imputation. NULL uses "euclidean" for K-NN and "regularized" for PCA.

cores

Integer. Number of cores for K-NN imputation only, as described under Parallelization.

.progress

Logical. If TRUE, show progress.

min_group_size

Integer or NULL. Minimum total number of columns per group, counting both features and auxiliary columns. Groups smaller than this are padded with columns sampled at random from the other grouped columns of obj.

colmax

Numeric scalar between 0 and 1. Columns with a proportion of missing values greater than colmax take no part in the imputation, as described under Column mean fill.

post_imp

Logical. If TRUE, column means replace the missing values that remain after imputation, as described under Column mean fill.

dist_pow

Numeric. Power used to penalize more distant neighbors in the weighted average, where 0 gives an unweighted average. The weighting rule is given under Details in knn_imp().

scale

Logical. If TRUE, columns are scaled to unit variance.

coeff.ridge

Numeric. The ridge regularization for method = "regularized", ignored otherwise. Values below 1 move toward EM PCA, and values above 1 move toward mean imputation.

threshold

Numeric. Convergence threshold.

row.w

Numeric vector, "n_miss", or NULL. The row weights, normalized to sum to 1: positive values of length nrow(obj), "n_miss" to down-weight rows with more missing values, or NULL for equal weights.

seed

Integer, numeric, or NULL. Random seed used when padding small groups and, for PCA imputation, passed to pca_imp().

nb.init

Integer. Number of initializations. The first is always mean imputation, and the others are random.

maxiter

Integer. Maximum number of iterations.

miniter

Integer. Minimum number of iterations, at most maxiter.

solver

Character. One of "auto", "exact", or "lobpcg". The eigensolver. "auto" uses "exact" for small problems and otherwise runs a short timed probe, picking "lobpcg" only when it is clearly faster. With nb.init > 1, the choice from the first initialization is reused. See the PCA Performance tips section.

lobpcg_control

A list or NULL. LOBPCG control options, from lobpcg_control() or as a plain named list, or NULL for the defaults. Ignored when solver = "exact".

clamp

Numeric vector of length 2 or NULL. The bounds c(lower, upper) for PCA-imputed values, such as c(0, 1) for DNA methylation beta values, or NULL for none. Use -Inf or Inf for a one-sided bound. Observed values are not clamped.

pin_blas

Logical. If TRUE, pin BLAS threads to 1 on the mirai daemons in a parallel run. Defaults to TRUE.

on_infeasible

Character. One of "error", "skip", or "mean". The action for a group that is infeasible for imputation, for example because k or ncp is too large for the columns that colmax leaves. Defaults to "error".

Details

Imputing each group on its own can reduce the runtime for large matrices.

Specify k and related arguments to use K-NN imputation, or ncp and related arguments to use PCA imputation. If both k and ncp are NULL, group$parameters must supply either k or ncp for every group. Passing an argument of the other method, such as scale with k, is an error.

Group-specific parameters in group$parameters take priority over global arguments, and global arguments fill in the parameters a group does not set. All groups must use the same imputation method. A global argument shared with knn_imp() or pca_imp() that is NULL takes that function's default.

Per-group k is capped at the group's column count minus one, counting features and auxiliary columns. Per-group ncp is capped at the smaller of that cap and nrow(obj) - 2. group_imp() warns when it caps a value.

A group is infeasible when it is too small for any valid k or ncp, or when knn_imp() or pca_imp() cannot impute it, for example because colmax leaves too few columns. With on_infeasible = "skip", an infeasible group keeps its missing values. With "mean", column means fill them, and with "error", group_imp() stops with an error. A group whose features have no missing values is not imputed and is never infeasible. An infeasible group adds nothing to the mean_filled_cols and mean_filled_cells attributes of the result.

With subset, the result holds only the subset columns, in the order they have in obj. The other features still take part in the imputation, as auxiliary columns of their groups.

The mirai daemons run R's "L'Ecuyer-CMRG" generator. So with nb.init > 1, a parallel PCA run draws different random initializations from a sequential run under R's default generator. The two agree when the session also runs RNGkind("L'Ecuyer-CMRG").

Value

A slideimp_results object: a numeric matrix with the rows of obj and the columns that subset selects, with the missing values of the grouped features imputed.

Parallelization

Column mean fill

A column with a proportion of missing values greater than colmax takes no part in the imputation. The method neither uses the column to impute other columns nor imputes it.

With post_imp = TRUE, column means replace the missing values that remain after the method has run. Two kinds of missing value can remain: the missing values of the columns that took no part, and the cells for which the method found no value. Each column mean is the mean of the column's observed values. With post_imp = FALSE, both kinds stay missing.

The result records what the column means replaced, in two attributes:

Both attributes are empty when no column mean was used. print() reports them when they are not empty.

Missing values and non-finite input

obj must be a double matrix. An integer or logical matrix is rejected, not converted. Convert one with storage.mode(obj) <- "double".

NA and NaN are both treated as missing. The package does not distinguish between them.

Inf and -Inf are rejected on entry, and so is a column with no observed values (every cell NA or NaN). Locate them with which(is.infinite(obj), arr.ind = TRUE) and which(colSums(!is.na(obj)) == 0).

PCA Performance tips

Three arguments set the speed: solver, threshold, and scale. Tune these first, then the accuracy arguments ncp and coeff.ridge, on a representative subset.

Exact vs. LOBPCG. "lobpcg" suits large, approximately low-rank matrices with small ncp. "exact" suits small matrices, such as slide_imp() windows, where it is faster. It is also more reliable: it always converges, to eigenvectors exact to machine precision, while LOBPCG stops at the tolerance set in lobpcg_control() and can take many iterations, or reach maxiter, when the eigenvalues around the ncp-th one are close together. The warm start makes each later LOBPCG solve cheap: pca_imp() starts LOBPCG from the previous eigenblock and search direction, so once the imputed values stabilize, each solve takes a few iterations. The gain grows with the number of EM iterations, whatever the rank. solver = "auto", the default, chooses between the two and is a safe start.

Threshold. The default 1e-6 is conservative. 1e-5 is often faster and gives very similar values.

Scale. For columns on a common scale, such as DNA methylation beta values in ⁠[0, 1]⁠, scale = FALSE can be faster and more accurate.

BLAS. On Windows, the BLAS that ships with R can be slow, and OpenBLAS can replace it.

See Speeding up PCA imputation for the full workflow.

Note

A platform name for group, such as "EPICv2" or "EPICv2_deduped", needs the optional slideimp.extra package. Its slideimp_arrays object lists the supported platforms.

See Also

Examples

set.seed(1234)
to_test <- sim_mat(10, 20, perc_total_na = 0.05, perc_col_na = 1)
obj <- to_test$input
group <- to_test$col_group
head(group)

# Simple grouped K-NN imputation
results <- group_imp(obj, group = group, k = 2, .progress = FALSE)
results

# Impute only a subset of features
subset_features <- sample(to_test$col_group$feature, size = 10)
knn_subset <- group_imp(
  obj,
  group = group,
  subset = subset_features,
  k = 2,
  .progress = FALSE
)

# Use prep_groups() to inspect and edit per-group parameters
prepped <- prep_groups(colnames(obj), group)
prepped$parameters <- lapply(seq_len(nrow(prepped)), function(i) list(k = 2))
prepped$parameters[[2]]$k <- 4
knn_grouped <- group_imp(obj, group = prepped, .progress = FALSE)


# PCA imputation with mirai parallelism
mirai::daemons(2)
pca_grouped <- group_imp(obj, group = group, ncp = 2)
mirai::daemons(0)
pca_grouped


K-Nearest Neighbor Imputation for Numeric Matrices

Description

Impute missing values in a numeric matrix with K-nearest neighbors (K-NN), searching the whole matrix for neighbors.

Usage

knn_imp(
  obj,
  k,
  colmax = 0.9,
  method = c("euclidean", "manhattan"),
  cores = 1,
  post_imp = TRUE,
  subset = NULL,
  dist_pow = 0,
  .progress = FALSE
)

Arguments

obj

A double matrix. Samples are in rows and features in columns.

k

Integer. Number of nearest neighbors for K-NN imputation.

colmax

Numeric scalar between 0 and 1. Columns with a proportion of missing values greater than colmax take no part in the imputation, as described under Column mean fill.

method

Character. One of "euclidean" or "manhattan". The distance used to find neighbors, as defined under Details.

cores

Integer. Number of cores for K-NN imputation. Defaults to 1.

post_imp

Logical. If TRUE, column means replace the missing values that remain after imputation, as described under Column mean fill.

subset

Optional character or integer vector. The columns to impute and return, by name or by number, or NULL for every column. Defaults to NULL.

dist_pow

Numeric. Power used to penalize more distant neighbors in the weighted average, where 0 gives an unweighted average. The weighting rule is given under Details in knn_imp().

.progress

Logical. If TRUE, show imputation progress.

Details

knn_imp() imputes each column from the k columns nearest to it, found by an exact brute-force search. The distance between the target column and a candidate column is a mean over the rows where both are observed. Candidates that share different numbers of rows with the target therefore stay comparable. method = "euclidean" averages squared differences and takes no square root. method = "manhattan" averages absolute differences.

A candidate that shares no observed row with the target is never a neighbor. A column can therefore have fewer than k neighbors, or none, and K-NN does not impute a column with none.

A column with few observed values can be selected as a neighbor because it agrees with the target on one or two shared rows. Such a neighbor has no value at most of the rows to impute. A lower colmax keeps these columns out of the neighbors.

When dist_pow > 0, imputed values are distance-weighted averages of the selected neighbors: a neighbor at distance d is weighted (d_min / d)^dist_pow, where d_min is the smallest positive distance among the neighbors chosen for that column. d_min cancels out of the average and only keeps the largest weight at 1.

Under "euclidean", d is a mean squared difference, so weighting by 1 / d^dist_pow equals weighting by 1 / d^(2 * dist_pow) on the usual, square-rooted euclidean distance. A dist_pow tuned for one method therefore does not carry over to the other.

Neighbors are selected once per column. A neighbor that is missing at a row drops out of the average for that row, which is taken over the neighbors observed there. K-NN does not impute a row where none of the neighbors is observed.

With dist_pow > 0, a neighbor at distance zero agrees with the target on every shared row and would take an infinite weight. It takes weight 1 instead, and the other neighbors take a small positive weight. Exact matches therefore dominate the average, but the other neighbors stay in it. When every neighbor is at distance zero, all weights are 1.

The result holds the subset columns in the order they have in obj. Every column within colmax can still be a neighbor, in subset or not. A name that is not in colnames(obj), or a subset that selects no column, is an error.

Value

A slideimp_results object: a numeric matrix with the rows of obj and the columns that subset selects, with missing values imputed.

K-NN performance optimization

Column mean fill

A column with a proportion of missing values greater than colmax takes no part in the imputation. The method neither uses the column to impute other columns nor imputes it.

With post_imp = TRUE, column means replace the missing values that remain after the method has run. Two kinds of missing value can remain: the missing values of the columns that took no part, and the cells for which the method found no value. Each column mean is the mean of the column's observed values. With post_imp = FALSE, both kinds stay missing.

The result records what the column means replaced, in two attributes:

Both attributes are empty when no column mean was used. print() reports them when they are not empty.

Missing values and non-finite input

obj must be a double matrix. An integer or logical matrix is rejected, not converted. Convert one with storage.mode(obj) <- "double".

NA and NaN are both treated as missing. The package does not distinguish between them.

Inf and -Inf are rejected on entry, and so is a column with no observed values (every cell NA or NaN). Locate them with which(is.infinite(obj), arr.ind = TRUE) and which(colSums(!is.na(obj)) == 0).

References

Troyanskaya O, Cantor M, Sherlock G, Brown P, Hastie T, Tibshirani R, Botstein D, Altman RB (2001). Missing value estimation methods for DNA microarrays. Bioinformatics, 17(6), 520-525. doi:10.1093/bioinformatics/17.6.520

See Also

group_imp() to impute within feature groups.

Examples

set.seed(123)
obj <- sim_mat(20, 20, perc_col_na = 1)$input
sum(is.na(obj))

# Select `k` with `tune_imp()`.
result <- knn_imp(obj, k = 10)
result

# Impute and return only the first three columns
knn_imp(obj, k = 10, subset = 1:3)


LOBPCG Eigensolver Control Options

Description

Construct a validated list of control options for the LOBPCG eigensolver used by pca_imp(). Most users do not need to call it.

Usage

lobpcg_control(warmup_iters = 10L, tol = 1e-09, maxiter = 20)

Arguments

warmup_iters

Integer. Number of initial pca_imp() iterations that use the exact eigensolver before LOBPCG starts. Must be non-negative.

tol

Numeric. Convergence tolerance for the LOBPCG eigensolver. Must be non-negative and finite.

maxiter

Integer. Maximum number of LOBPCG iterations per eigenvalue solve. Must be non-negative, and positive when pca_imp() runs with solver = "auto" or "lobpcg". Use solver = "exact", not maxiter = 0, to select the exact solver.

Details

Under solver = "auto", pca_imp() raises a warmup_iters that was not set for a large ncp, up to 50. Set warmup_iters to keep a fixed value.

Value

A slideimp_lobpcg_control object: a named list with warmup_iters, tol, and maxiter.

Examples

set.seed(123)
obj <- sim_mat(10, 10)$input

# Use all defaults
lobpcg_control()

# Override a single option
lobpcg_control(maxiter = 50)

# Force the exact solver from pca_imp()
pca_imp(obj, ncp = 2, solver = "exact")

# Pass directly to pca_imp()
pca_imp(obj, ncp = 2, lobpcg_control = lobpcg_control(tol = 1e-8))

# Or use a named list
pca_imp(obj, ncp = 2, lobpcg_control = list(maxiter = 50))


Column or Row Missing Counts and Proportions

Description

Calculate the number or proportion of missing values per column or per row of a numeric matrix, without allocating a logical matrix the size of obj.

Usage

mat_miss(obj, col = TRUE, prop = FALSE)

Arguments

obj

A double matrix.

col

Logical. Whether to compute per column (TRUE) or per row (FALSE).

prop

Logical. Whether to return missing-value proportions (TRUE) or counts (FALSE).

Details

NA and NaN both count as missing. Inf and -Inf do not.

Value

When prop = FALSE, an integer vector of missing-value counts. When prop = TRUE, a double vector of missing-value proportions. The vector has one element per column when col = TRUE, or per row otherwise, named from colnames(obj) or rownames(obj) when set.

Examples

obj <- matrix(c(1, NA, 3, 4, NA, 6, NA, 8, 9), nrow = 3)
obj

# column missing counts
mat_miss(obj)

# row missing counts
mat_miss(obj, col = FALSE)

# column missing proportions
mat_miss(obj, prop = TRUE)


Multiple Imputation by Bayesian PCA

Description

Draw multiple imputations for the missing values of a numeric matrix under a low-rank model using the Audigier, Husson and Josse (BayesMIPCA) data-augmentation sampler.

Usage

mipca(
  obj,
  rank,
  transform,
  subset = NULL,
  keep_state = FALSE,
  prop_diag = 0.5,
  iter_sampling = 100,
  iter_warmup = 100,
  thin = 1,
  nu = Inf,
  chains = 4L,
  refresh = 0L,
  spectra = spectra_opts(),
  init = 1,
  seed = NULL,
  abb = NULL
)

Arguments

obj

A double matrix with samples in rows and features in columns. Row and column names are required and must be unique. NA and NaN values are imputed.

rank

Integer. Number of principal components in the model. Use mipca_tune() to choose the rank on held-out values.

transform

Character or a transform object. The scale the model is fitted on: "identity", "logit_biwhiten", or an object from tf_identity(), tf_sv() or tf_biwhiten(). See Details in mipca().

subset

Optional character or integer vector. The columns whose draws are kept and returned, by name or by number, or NULL for every column. Defaults to NULL.

keep_state

Logical. If TRUE, return a fit that update() can extend at the cost of memory. Defaults to FALSE.

prop_diag

Numeric scalar between 0 and 1. Proportion of each column's missing values on which summary() computes Rhat and ESS. 0 is refused. Defaults to 0.5.

iter_sampling

Integer. Number of draws kept per chain. Defaults to 100.

iter_warmup

Integer. Number of iterations discarded at the start of each chain, 0 or more. Defaults to 100.

thin

Integer. After warmup, each chain keeps one iteration in every thin, so it runs iter_sampling * thin iterations to keep iter_sampling draws. Defaults to 1.

nu

Numeric. Degrees of freedom of the noise drawn for a missing value: Inf for Gaussian noise, or a number above 2 for Student-t noise of the same variance. Defaults to Inf. Can be chosen by mipca_tune().

chains

Integer. Number of independent chains. Defaults to 4.

refresh

Integer. Print a progress line every refresh iterations of each chain, or 0 for none. Defaults to 0.

spectra

A spectra_opts object. Settings for the eigensolver, from spectra_opts().

init

Numeric. How widely each chain's starting values are spread: each missing value starts at a random draw whose standard deviation is init times its column's observed standard deviation. Must be positive. Defaults to 1.

seed

Integer, numeric, or NULL. Seed for the sampler. With NULL, the seed is drawn from R's random number stream. Defaults to NULL.

abb

Optional character or integer vector. Columns to draw by approximate Bayesian bootstrap instead of by the model. abb_cols() proposes them. Defaults to NULL.

Details

The transform. "identity" fits the values as they are. "logit_biwhiten" is for proportions such as DNAm beta values, and every observed value must lie in ⁠[0, 1]⁠; see tf_sv() and tf_biwhiten(). Draws are returned on the scale of obj.

Which columns take part. Every column of obj takes part in the model, and every missing value is drawn at every iteration. subset selects only which columns' draws are kept. The result holds the selected columns in the order they have in obj.

Size. The draws hold one number per missing value kept, per chain, per draw. Keep fewer columns with subset, or ask for fewer chains or iter_sampling. If the selected columns have no missing values, the fit is returned without sampling.

Reproducibility. With the same seed, or the same set.seed() before a call with seed = NULL, the draws are the same.

Value

With keep_state = FALSE, a finalized fit of class si_mi. It holds chains * iter_sampling draws of every missing value in the selected columns. Use:

With keep_state = TRUE, a resumable fit of class si_mi_pca. Extend it with update(), then finish it with mipca_finalize().

Performance

Linking R to a faster BLAS can make the sampler significantly faster: OpenBLAS on Windows, or Apple's Accelerate on macOS.

References

Audigier V, Husson F, Josse J (2016). Multiple imputation for continuous variables using a Bayesian principal component analysis. Journal of Statistical Computation and Simulation, 86(11), 2140-2156. doi:10.1080/00949655.2015.1104683

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)
fit <- mipca(sim$input, rank = 2, transform = "logit_biwhiten", seed = 1)
fit
completed <- lapply(c(1, 200, 400), function(b) as.matrix(fit, draw = b))
summary(fit)

Extend or Finalize a Resumable Bayesian PCA Fit

Description

A fit made with keep_state = TRUE is resumable. update() adds draws to each of its chains. mipca_finalize() turns it into a finalized fit.

Usage

## S3 method for class 'si_mi_pca'
update(object, iter_sampling, ...)

## S3 method for class 'si_mi'
update(object, ...)

mipca_finalize(x, thin = 1L, prop_diag = 0.5)

Arguments

object

A si_mi_pca object. A resumable fit, from mipca() or mipca_fit() with keep_state = TRUE.

iter_sampling

Integer. Number of draws to add to each chain.

...

Not used.

x

A si_mi_pca object. A resumable fit, from mipca() or mipca_fit() with keep_state = TRUE.

thin

Integer. Keep every thin-th draw of each chain, starting at the first. Defaults to 1.

prop_diag

Numeric scalar between 0 and 1. Proportion of each column's missing values on which summary() computes Rhat and ESS. 0 is refused. Defaults to 0.5.

Details

Extending. update() continues each chain from where it stopped, without a new warmup. The rank, nu, transform, thinning, eigensolver settings and subset of the fit stay as they were. A fit of a draws extended by b holds the same draws, to rounding, as a fit of a + b draws made in one run with the same seed.

In place. update() changes object itself and returns it invisibly, so update(fit, iter_sampling = 100) needs no assignment. b <- fit does not copy a resumable fit: b and fit are the same fit, and extending one extends both.

Finalizing. mipca_finalize() keeps every thin-th draw and computes Rhat and ESS on prop_diag of each column's missing values. Use the si_mi fit it returns: the resumable fit can no longer be used.

Failures. If update() fails partway, the fit may no longer be usable, and print() says so. Fit again with mipca().

Finalized fits. A si_mi fit holds no saved state. update() and mipca_finalize() refuse it.

Value

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)
fit <- mipca(sim$input, rank = 2, transform = "logit_biwhiten", keep_state = TRUE, seed = 1)
fit

# 100 more draws per chain, in place
update(fit, iter_sampling = 100)
fit

# Keep every second draw
final <- mipca_finalize(fit, thin = 2)
final

Fit Bayesian PCA Imputation at a Tuned Rank

Description

Fit mipca() at a rank from a mipca_tune() table, with the nu, transform and sampler settings of that tuning run.

Usage

mipca_fit(
  object,
  obj,
  rank = NULL,
  ...,
  chains,
  iter_warmup,
  iter_sampling,
  thin,
  spectra,
  init,
  refresh = 100L,
  keep_state = FALSE,
  prop_diag = 0.5,
  seed = NULL,
  nu = NULL,
  transform,
  abb
)

Arguments

object

A si_tune object. The table mipca_tune() returns, or a subset of its rows.

obj

A double matrix. The matrix object was tuned on, passed again. The table does not carry it.

rank

Integer or NULL. A rank in object. With NULL, the rank with the lowest crps. Defaults to NULL.

...

Not used. Name every argument after rank.

chains

Integer. Number of independent chains. Taken from object when left out.

iter_warmup

Integer. Number of iterations discarded at the start of each chain, 0 or more. Taken from object when left out.

iter_sampling

Integer. Number of draws kept per chain. Taken from object when left out.

thin

Integer. After warmup, each chain keeps one iteration in every thin, as in mipca(). Taken from object when left out.

spectra

A spectra_opts object. Settings for the eigensolver, from spectra_opts(). Taken from object when left out.

init

Numeric. How widely each chain's starting values are spread, as in mipca(). Taken from object when left out.

refresh

Integer. Print a progress line every refresh iterations of each chain, or 0 for none. Defaults to 100.

keep_state

Logical. If TRUE, return a fit that update() can extend at the cost of memory. Defaults to FALSE.

prop_diag

Numeric scalar between 0 and 1. Proportion of each column's missing values on which summary() computes Rhat and ESS. 0 is refused. Defaults to 0.5.

seed

Integer, numeric, or NULL. Seed for the sampler. With NULL, the seed is drawn from R's random number stream. Defaults to NULL.

nu

Numeric or NULL. Degrees of freedom of the noise drawn for a missing value, as in mipca(). With NULL, the implied_nu of rank in object, or 5 if it is lower. Defaults to NULL.

transform, abb

Not used. The fit uses the transform and abb stored in object. To change them, run mipca_tune() again, or call mipca().

Details

The matrix. obj must be the same matrix object was tuned on. Another matrix is refused. The held-out values are not held out in the fit: every observed value of obj is used.

The rank and nu. With rank = NULL, the rank is the one with the lowest crps among the ranks whose fit did not fail. A given rank must be in object. When the implied_nu is below 5, the fit uses 5 and a message says so. A nu that is given is used as it is, with the warning mipca() gives below 5.

The same fit as mipca(). The fit is the one mipca() returns for the same obj, rank, nu, transform, abb, sampler settings and seed.

Value

As mipca(): with keep_state = FALSE, a finalized fit of class si_mi. With keep_state = TRUE, a resumable fit of class si_mi_pca.

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)
tuned <- mipca_tune(
  sim$input,
  rank = 1:3,
  transform = "logit_biwhiten",
  n_cols = 10,
  seed = 1
)

# The rank with the lowest crps
fit <- mipca_fit(tuned, sim$input, refresh = 0, seed = 1)
fit

# Another tuned rank, with more draws per chain
fit3 <- mipca_fit(tuned, sim$input, rank = 3, iter_sampling = 200, refresh = 0, seed = 1)

Bayesian PCA Imputation on a Flanking Window per Column

Description

Impute each target column from the columns near it by location, such as the CpGs within some distance of a CpG. mipca_flank_plan() finds each target's window, and mipca_flank() fits mipca() on each window and keeps the target's draws.

Usage

mipca_flank_plan(
  obj,
  location,
  window_size,
  subset,
  min_window_n,
  colmax = 0.95,
  abb = NULL
)

## S3 method for class 'si_flank_plan'
print(x, n = 10L, ...)

mipca_flank_window(plan, subset)

mipca_flank(
  plan,
  rank,
  seed,
  transform,
  prop_diag = 0.5,
  iter_sampling = 100,
  iter_warmup = 100,
  thin = 1,
  nu = Inf,
  chains = 4L,
  spectra = spectra_opts(),
  init = 1,
  .progress = TRUE
)

Arguments

obj

A double matrix with samples in rows and features in columns. Row and column names are required and must be unique. NA and NaN values are imputed.

location

Numeric. The position of each column of obj, such as a genomic coordinate, sorted in ascending order.

window_size

Numeric. Distance from the target, in the units of location, that its window covers on each side.

subset

Character or integer vector. In mipca_flank_plan(), the target columns. In mipca_flank_window(), one target of the plan. By name or by number.

min_window_n

Integer. Minimum number of columns in a window, the target included, at least 2. mipca_flank() needs at least rank + 2.

colmax

Numeric scalar between 0 and 1. Columns missing a larger proportion of their values are left out of every window, and are not imputed. Defaults to 0.95.

abb

Optional character or integer vector. Columns to draw by approximate Bayesian bootstrap instead of by the model. They are left out of every window. abb_cols() proposes them. Defaults to NULL.

x

A si_flank_plan object.

n

Integer. Number of rows of the table to print. Defaults to 10.

...

Not used.

plan

A si_flank_plan object. The plan mipca_flank_plan() returns.

rank

Integer. Number of principal components in the model. Use mipca_tune() to choose the rank on held-out values.

seed

Integer. Seed for the sampler.

transform

Character or a transform object. The scale the model is fitted on: "identity", "logit_biwhiten", or an object from tf_identity(), tf_sv() or tf_biwhiten(). See Details in mipca().

prop_diag

Numeric scalar between 0 and 1. Proportion of each column's missing values on which summary() computes Rhat and ESS. 0 is refused. Defaults to 0.5.

iter_sampling

Integer. Number of draws kept per chain. Defaults to 100.

iter_warmup

Integer. Number of iterations discarded at the start of each chain, 0 or more. Defaults to 100.

thin

Integer. After warmup, each chain keeps one iteration in every thin, so it runs iter_sampling * thin iterations to keep iter_sampling draws. Defaults to 1.

nu

Numeric. Degrees of freedom of the noise drawn for a missing value: Inf for Gaussian noise, or a number above 2 for Student-t noise of the same variance. Defaults to Inf. Can be chosen by mipca_tune().

chains

Integer. Number of independent chains. Defaults to 4.

spectra

A spectra_opts object. Settings for the eigensolver, from spectra_opts().

init

Numeric. How widely each chain's starting values are spread: each missing value starts at a random draw whose standard deviation is init times its column's observed standard deviation. Must be positive. Defaults to 1.

.progress

Logical. If TRUE, report progress through the windows. Defaults to TRUE.

Details

The window. A target's window is the columns within window_size of it on location, on both sides. Columns that are constant, have fewer than two observed values, miss more than colmax of their values, or are listed in abb are left out.

The columns read. mipca_flank_plan() reads a column only if a window can hold it, or if it is a target listed in abb, and refuses an Inf in any column it reads. It does not read the other columns, so an Inf in one of them is not refused. mipca_flank() reads only the targets listed in abb and the columns of the windows it fits.

The plan. plan$targets has one row per target, in column order: its column number target and name, its number of missing values n_miss, the first and last column of its window start and end, the number of columns in the window window_n, and its status:

A plan in which no target with missing values can be imputed is refused. print() shows the count per status and the first n rows.

The rank and nu. Choose them on one target's window: pass mipca_flank_window(plan, target) to mipca_tune(), then give the rank and nu to mipca_flank(). The default n_cols of mipca_tune() holds out values in at least 50 columns, more than a window may have, so pass a smaller n_cols there.

The fit. The result holds the targets in the order of plan$targets. Its completed matrices hold NA where a target was not imputed, and print() counts those columns. A target's draws depend on seed and its column number in obj only, so dropping another target from the plan leaves them unchanged.

Failures. A window whose fit fails stops the run, with the target's name in the message.

Value

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 200, beta = TRUE)
obj <- sim$input
location <- seq_len(ncol(obj))

# Windows of 20 columns on each side of three targets
plan <- mipca_flank_plan(
  obj,
  location,
  window_size = 20,
  subset = c(49, 102, 150),
  min_window_n = 10
)
plan

# One target's window, to choose the rank on
win <- mipca_flank_window(plan, 150)
dim(win)

fit <- mipca_flank(plan, rank = 2, seed = 1, transform = "logit_biwhiten")
fit

Choose the Rank of Bayesian PCA Imputation on Held-Out Values

Description

Hide a set of observed values, fit mipca() at each candidate rank, and score how well each rank's draws predict the hidden values. Pass the result to mipca_fit() to fit the best rank.

Usage

mipca_tune(
  obj,
  rank,
  na_loc = NULL,
  n_cols = NULL,
  n_rows = 4L,
  transform,
  n_diag = 10000L,
  iter_warmup = 100L,
  iter_sampling = 100L,
  chains = 4L,
  thin = 1,
  init = 1,
  refresh = 0L,
  spectra = spectra_opts(),
  seed = NULL,
  abb = NULL
)

## S3 method for class 'si_tune'
print(x, ...)

Arguments

obj

A double matrix with samples in rows and features in columns. Row and column names are required and must be unique. NA and NaN values are imputed.

rank

Integer vector. The candidate ranks, each a whole number of at least 1, given once.

na_loc

A list or NULL. The values to hold out, as one two-column matrix of row and column positions in a list, the form sample_na_loc() returns with n_reps = 1. Each must be an observed value of obj. With NULL, the positions are drawn from n_cols and n_rows. Defaults to NULL.

n_cols

Integer or NULL. Number of columns that receive held-out values. With NULL, 10% of the columns, at least 50 and at most 500. Defaults to NULL.

n_rows

Integer. Number of held-out values in each of the n_cols columns. Leave it out when na_loc is given. Defaults to 4.

transform

Character or a transform object. The scale the model is fitted on: "identity", "logit_biwhiten", or an object from tf_identity(), tf_sv() or tf_biwhiten(). See Details in mipca().

n_diag

Integer. Number of missing values, held-out values included, on which Rhat and ESS are computed for each rank. They are sampled across columns with few and with many missing values. Defaults to 10000.

iter_warmup

Integer. Number of iterations discarded at the start of each chain, 0 or more. Defaults to 100.

iter_sampling

Integer. Number of draws kept per chain. Defaults to 100.

chains

Integer. Number of independent chains. Defaults to 4.

thin

Integer. After warmup, each chain keeps one iteration in every thin, so it runs iter_sampling * thin iterations to keep iter_sampling draws. Defaults to 1.

init

Numeric. How widely each chain's starting values are spread: each missing value starts at a random draw whose standard deviation is init times its column's observed standard deviation. Must be positive. Defaults to 1.

refresh

Integer. Print a progress line every refresh iterations of each chain, or 0 for none. Defaults to 0.

spectra

A spectra_opts object. Settings for the eigensolver, from spectra_opts().

seed

Integer, numeric, or NULL. Seed for the held-out values and the sampler. With NULL, both are drawn from R's random number stream. Defaults to NULL.

abb

Optional character or integer vector. Columns to draw by approximate Bayesian bootstrap instead of by the model. abb_cols() proposes them. Defaults to NULL.

x

A si_tune object.

...

Not used.

Details

The held-out values. With na_loc = NULL, sample_na_loc() picks n_cols columns and hides n_rows observed values in each. A column is eligible if it is not constant and has at least n_rows + 2 observed values. Every rank is fitted on the same matrix, with the same values hidden, and is scored on those values only. The holdout needs more than two values. The abb columns take no part in tuning, and no value in them is held out.

The rank. crps is the continuous ranked probability score of each held-out value against its draws, on the scale of obj, averaged over the held-out values. A lower score is better. mipca_fit() fits the rank with the lowest crps unless it is given another.

The noise. implied_nu is the Student-t degrees of freedom that the spread of the held-out values implies, Inf when they look Gaussian. implied_lo and implied_hi are its bootstrap interval. implied_nu is the raw reading. mipca_fit() fits with nu set to implied_nu, or to 5 if the reading is lower.

Failures. A rank whose fit fails does not stop the call. Its row holds the message in error, and its scores are NA.

Reproducibility. With the same seed, the held-out values and the table are the same. A given seed leaves R's random number stream as it was. With seed = NULL, the same set.seed() before the call gives the same table.

Value

A data frame of class si_tune, one row per rank, with columns:

The table also carries the transform, the sampler settings, abb and the held-out positions, which mipca_fit() reads.

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)
tuned <- mipca_tune(
  sim$input,
  rank = 1:3,
  transform = "logit_biwhiten",
  n_cols = 10,
  seed = 1
)
tuned
fit <- mipca_fit(tuned, sim$input, seed = 1)
fit

PCA Imputation for Numeric Matrices

Description

Impute missing values in a numeric matrix with regularized or expectation-maximization (EM) PCA imputation. The eigensolver can be LOBPCG, warm-started from the previous eigenblock and search direction.

Usage

pca_imp(
  obj,
  ncp = 2,
  scale = TRUE,
  method = c("regularized", "EM"),
  coeff.ridge = 1,
  row.w = NULL,
  threshold = 1e-06,
  seed = NULL,
  nb.init = 1,
  maxiter = 1000,
  miniter = 5,
  solver = c("auto", "exact", "lobpcg"),
  lobpcg_control = NULL,
  colmax = 0.9,
  post_imp = TRUE,
  clamp = NULL,
  subset = NULL,
  .progress = FALSE
)

Arguments

obj

A double matrix. Samples are in rows and features in columns.

ncp

Integer. Number of principal components used to impute missing values.

scale

Logical. If TRUE, columns are scaled to unit variance.

method

Character. One of "regularized" or "EM". The PCA imputation method.

coeff.ridge

Numeric. The ridge regularization for method = "regularized", ignored otherwise. Values below 1 move toward EM PCA, and values above 1 move toward mean imputation.

row.w

Numeric vector, "n_miss", or NULL. The row weights, normalized to sum to 1: positive values of length nrow(obj), "n_miss" to down-weight rows with more missing values, or NULL for equal weights.

threshold

Numeric. Convergence threshold.

seed

Integer, numeric, or NULL. Random seed for reproducibility. As in missMDA::imputePCA(), initialization i is seeded with seed * (i - 1). So seed = 0 gives every random initialization the same start, and nb.init then yields two distinct solves: the mean initialization and one random one. With nb.init > 1, seed can be at most .Machine$integer.max %/% (nb.init - 1).

nb.init

Integer. Number of initializations. The first is always mean imputation, and the others are random.

maxiter

Integer. Maximum number of iterations.

miniter

Integer. Minimum number of iterations, at most maxiter.

solver

Character. One of "auto", "exact", or "lobpcg". The eigensolver. "auto" uses "exact" for small problems and otherwise runs a short timed probe, picking "lobpcg" only when it is clearly faster. With nb.init > 1, the choice from the first initialization is reused. See the PCA Performance tips section.

lobpcg_control

A list or NULL. LOBPCG control options, from lobpcg_control() or as a plain named list, or NULL for the defaults. Ignored when solver = "exact".

colmax

Numeric scalar between 0 and 1. Columns with a proportion of missing values greater than colmax take no part in the imputation, as described under Column mean fill.

post_imp

Logical. If TRUE, column means replace the missing values that remain after imputation, as described under Column mean fill.

clamp

Numeric vector of length 2 or NULL. The bounds c(lower, upper) for PCA-imputed values, such as c(0, 1) for DNA methylation beta values, or NULL for none. Use -Inf or Inf for a one-sided bound. Observed values are not clamped.

subset

Optional character or integer vector. The columns to impute and return, by name or by number, or NULL for every column. Defaults to NULL.

.progress

Logical. If TRUE, show imputation progress.

Details

pca_imp() reimplements the PCA imputation method from the missMDA package by Francois Husson and Julie Josse, based on Josse and Husson (2016).

A column whose observed values do not vary takes no part in PCA imputation. Column mean fill treats it like a column over colmax, in post_imp and in the mean_filled_cols attribute.

With subset, the result holds only the selected columns, in the order they have in obj. The other columns take part in the imputation as they do without subset. So subset makes the result smaller, not the imputation faster. A name that is not in colnames(obj), or a subset that selects no column, is an error.

Value

A slideimp_results object: a numeric matrix with the rows of obj and the columns that subset selects, with missing values imputed.

PCA Performance tips

Three arguments set the speed: solver, threshold, and scale. Tune these first, then the accuracy arguments ncp and coeff.ridge, on a representative subset.

Exact vs. LOBPCG. "lobpcg" suits large, approximately low-rank matrices with small ncp. "exact" suits small matrices, such as slide_imp() windows, where it is faster. It is also more reliable: it always converges, to eigenvectors exact to machine precision, while LOBPCG stops at the tolerance set in lobpcg_control() and can take many iterations, or reach maxiter, when the eigenvalues around the ncp-th one are close together. The warm start makes each later LOBPCG solve cheap: pca_imp() starts LOBPCG from the previous eigenblock and search direction, so once the imputed values stabilize, each solve takes a few iterations. The gain grows with the number of EM iterations, whatever the rank. solver = "auto", the default, chooses between the two and is a safe start.

Threshold. The default 1e-6 is conservative. 1e-5 is often faster and gives very similar values.

Scale. For columns on a common scale, such as DNA methylation beta values in ⁠[0, 1]⁠, scale = FALSE can be faster and more accurate.

BLAS. On Windows, the BLAS that ships with R can be slow, and OpenBLAS can replace it.

See Speeding up PCA imputation for the full workflow.

Column mean fill

A column with a proportion of missing values greater than colmax takes no part in the imputation. The method neither uses the column to impute other columns nor imputes it.

With post_imp = TRUE, column means replace the missing values that remain after the method has run. Two kinds of missing value can remain: the missing values of the columns that took no part, and the cells for which the method found no value. Each column mean is the mean of the column's observed values. With post_imp = FALSE, both kinds stay missing.

The result records what the column means replaced, in two attributes:

Both attributes are empty when no column mean was used. print() reports them when they are not empty.

Missing values and non-finite input

obj must be a double matrix. An integer or logical matrix is rejected, not converted. Convert one with storage.mode(obj) <- "double".

NA and NaN are both treated as missing. The package does not distinguish between them.

Inf and -Inf are rejected on entry, and so is a column with no observed values (every cell NA or NaN). Locate them with which(is.infinite(obj), arr.ind = TRUE) and which(colSums(!is.na(obj)) == 0).

References

Josse J, Husson F (2013). Handling missing values in exploratory multivariate data analysis methods. Journal de la SFdS, 153(2), 79-99.

Josse J, Husson F (2016). missMDA: A Package for Handling Missing Values in Multivariate Data Analysis. Journal of Statistical Software, 70(1), 1-31. doi:10.18637/jss.v070.i01

See Also

Examples

set.seed(123)
obj <- sim_mat(10, 10)$input
sum(is.na(obj))
obj[1:4, 1:4]

# Five initializations: the first is mean imputation, the other four are
# random. Select `ncp` with `tune_imp()`.
pca_imp(obj, ncp = 2, nb.init = 5, seed = 123)

# Impute every column, but return only the first three
pca_imp(obj, ncp = 2, subset = 1:3)


Group Preparation for Imputation

Description

Normalize and validate a grouping specification for use with group_imp().

Usage

prep_groups(
  obj_cn,
  group,
  subset = NULL,
  min_group_size = 0,
  allow_unmapped = FALSE,
  seed = NULL
)

Arguments

obj_cn

Character. The column names of the data matrix, usually colnames(obj).

group

A data frame or a character scalar. The feature groups, in one of these forms:

  • A character scalar naming a supported Illumina platform, such as "EPICv2". This needs the slideimp.extra package.

  • A long-format data frame with columns group and feature.

  • A list-column data frame with a feature list-column. Optional list-columns are aux, for auxiliary feature names, and parameters, for group-specific parameter lists.

subset

Optional character vector. The features to impute, by name, or NULL for every grouped feature. A group's other features become its auxiliary columns, and a group left with no feature is dropped with a message.

min_group_size

Integer. Minimum number of columns per group, features and auxiliary columns together. Groups smaller than this are padded with columns sampled at random from the other grouped columns in obj_cn. If 0, no padding is performed.

allow_unmapped

Logical. If FALSE, every column in colnames(obj) must appear in group. If TRUE, columns with no group assignment are left untouched and are not used as auxiliary columns.

seed

Integer, numeric, or NULL. Random seed used when padding small groups.

Details

prep_groups() converts a long-format or list-column group to a slideimp_tbl, and pads small groups when min_group_size is above 0.

Let A be obj_cn and B be the union of all feature and auxiliary names in group. When allow_unmapped = FALSE, prep_groups() requires A \subseteq B: every name in obj_cn must appear in group.

Names in B but not in A, such as probes dropped in quality control, are removed from each group. Groups left with no features are dropped with a message.

Value

A data frame of class slideimp_tbl containing:

See Also

group_imp() to impute with the prepared groups.

Examples

sim <- sim_mat(n = 10, p = 20)
prepped <- prep_groups(colnames(sim$input), sim$col_group)
prepped


Print Method for slideimp_results Objects

Description

Print the output of knn_imp(), pca_imp(), group_imp(), or slide_imp().

Usage

## S3 method for class 'slideimp_results'
print(x, n = 6L, p = 6L, ...)

Arguments

x

A slideimp_results object.

n

Integer. Number of rows to print.

p

Integer. Number of columns to print.

...

Further arguments passed to print() for the preview.

Value

x, invisibly.

Examples

set.seed(1234)
mat <- sim_mat(n = 10, p = 10)
result <- knn_imp(mat$input, k = 5, .progress = FALSE)
class(result)
print(result, n = 6, p = 6)


Print Method for slideimp_sim Objects

Description

Print the output of sim_mat().

Usage

## S3 method for class 'slideimp_sim'
print(x, n = 6L, p = 6L, ...)

Arguments

x

A slideimp_sim object.

n

Integer. Number of rows of each component to show.

p

Integer. Number of columns of input to show.

...

Not used.

Value

x, invisibly.

Examples

set.seed(123)
sim_data <- sim_mat(n = 50, p = 10, rho = 0.5)
class(sim_data)
print(sim_data)


Print Method for slideimp_tbl Objects

Description

Print a slideimp_tbl data frame. Each cell of a list-column shows as its type and size.

Usage

## S3 method for class 'slideimp_tbl'
print(x, n = NULL, ...)

Arguments

x

A slideimp_tbl object.

n

Integer or NULL. Number of rows to show, 10 if NULL.

...

Further arguments passed to print() for the table.

Value

x, invisibly.

Examples

sim <- sim_mat(n = 10, p = 20)
tbl <- prep_groups(colnames(sim$input), sim$col_group)
class(tbl)
print(tbl)


Sample Missing-Value Locations with Constraints

Description

Draws matrix positions for NA injection. The positions respect row and column limits on missing values and skip constant columns.

Usage

sample_na_loc(
  obj,
  n_cols = NULL,
  n_rows = 2L,
  num_na = NULL,
  n_reps = 1L,
  rowmax = 0.9,
  colmax = 0.9,
  na_col_subset = NULL,
  max_attempts = 100
)

Arguments

obj

A double matrix.

n_cols

Integer or NULL. Number of columns that receive missing values.

n_rows

Integer. Minimum number of missing values per selected column.

num_na

Integer or NULL. Total number of missing values per repetition. When given, n_cols is ignored and the values are spread as evenly as possible over num_na %/% n_rows columns.

n_reps

Integer. Number of independent repetitions.

rowmax

Numeric scalar between 0 and 1. Maximum proportion of missing values per row after injection.

colmax

Numeric scalar between 0 and 1. Maximum proportion of missing values per column after injection.

na_col_subset

Optional character or integer vector. The columns that can receive missing values, by name or by number.

max_attempts

Integer. Maximum number of sampling attempts per repetition before an error.

Details

sample_na_loc() places the NA locations by a greedy random search. Every result meets these limits:

A column that cannot take n_rows missing values under these limits is skipped without an error.

When both n_cols and num_na are NULL, num_na defaults to 5% of the cells of obj, with a maximum of 500. The default never asks for more columns than the number that can take n_rows missing values.

Value

A list of length n_reps. Each element is a two-column integer matrix, with columns row and col, of the sampled NA locations.

See Also

Examples

set.seed(123)
mat <- matrix(runif(100), nrow = 10)

# Sample 5 missing values across 5 columns
locs <- sample_na_loc(mat, n_cols = 5, n_rows = 1)
locs

# Inject the missing values from the first repetition
mat[locs[[1]]] <- NA
mat


Simulated Numeric Matrix with Metadata

Description

sim_mat() generates random normal data with compound-symmetric column correlation, optionally scaled to ⁠[0, 1]⁠ column-wise. It also builds feature metadata for the columns and sample metadata for the rows, and sets a proportion of the cells to NA across a proportion of the columns.

Usage

sim_mat(
  n = 100,
  p = 100,
  rho = 0.5,
  n_col_groups = 2,
  n_row_groups = 1,
  perc_total_na = 0.1,
  perc_col_na = 0.5,
  beta = TRUE
)

Arguments

n

Integer. Number of rows, interpreted as samples. Defaults to 100.

p

Integer. Number of columns, interpreted as features. Defaults to 100.

rho

Numeric. Correlation between every pair of columns before scaling, at least 0 and below 1. Defaults to 0.5.

n_col_groups

Integer. Number of group labels drawn at random for the features. Defaults to 2.

n_row_groups

Integer. Number of group labels drawn at random for the samples. Defaults to 1.

perc_total_na

Numeric scalar between 0 and 1. Proportion of all matrix cells to set to NA. Defaults to 0.1.

perc_col_na

Numeric scalar between 0 and 1. Proportion of columns across which injected NA values are spread. Defaults to 0.5.

beta

Logical. If TRUE, scale values to the interval ⁠[0, 1]⁠ column-wise. Defaults to TRUE.

Value

A slideimp_sim object, a list with:

Examples

set.seed(123)
sim_data <- sim_mat(n = 50, p = 10, rho = 0.5)
sim_data


Sliding-Window K-NN or PCA Imputation

Description

Impute missing values in a numeric matrix whose columns are ordered by position, using K-NN or PCA imputation within sliding windows. For Illumina DNA methylation microarrays, use group_imp() instead.

Usage

slide_imp(
  obj,
  location,
  window_size,
  overlap_size = 0,
  flank = FALSE,
  min_window_n,
  subset = NULL,
  dry_run = FALSE,
  k = NULL,
  cores = 1,
  dist_pow = 0,
  ncp = NULL,
  scale = TRUE,
  coeff.ridge = 1,
  threshold = 1e-06,
  seed = NULL,
  row.w = NULL,
  nb.init = 1,
  maxiter = 1000,
  miniter = 5,
  solver = c("auto", "exact", "lobpcg"),
  lobpcg_control = NULL,
  clamp = NULL,
  method = NULL,
  .progress = TRUE,
  colmax = 0.9,
  post_imp = TRUE,
  on_infeasible = c("skip", "error", "mean")
)

Arguments

obj

A double matrix. Samples are in rows and features in columns.

location

Numeric. The position of each column of obj, such as a genomic coordinate, sorted in ascending order.

window_size

Numeric. The width of each window, in the units of location. With flank = TRUE, the distance each window reaches on each side of its feature.

overlap_size

Numeric. The overlap between consecutive windows, in the units of location, less than window_size. Ignored when flank = TRUE.

flank

Logical. If FALSE, slide windows across all columns. If TRUE, build one window around each column in subset, as described under Details.

min_window_n

Integer. The smallest number of columns, at least 2, that a window needs to be kept. k and ncp must be less than min_window_n.

subset

Optional character or integer vector. The columns to impute and return, by name or by number, or NULL for every column. Must be supplied when flank = TRUE. Defaults to NULL.

dry_run

Logical. If TRUE, return the windows that min_window_n and subset leave, as a slideimp_tbl, without imputing. k and ncp are not needed then.

k

Integer or NULL. Number of nearest neighbors for K-NN imputation.

cores

Integer. Number of cores for K-NN imputation. Defaults to 1.

dist_pow

Numeric. Power used to penalize more distant neighbors in the weighted average, where 0 gives an unweighted average. The weighting rule is given under Details in knn_imp().

ncp

Integer or NULL. Number of components for PCA imputation.

scale

Logical. If TRUE, columns are scaled to unit variance.

coeff.ridge

Numeric. The ridge regularization for method = "regularized", ignored otherwise. Values below 1 move toward EM PCA, and values above 1 move toward mean imputation.

threshold

Numeric. Convergence threshold.

seed

Integer, numeric, or NULL. Random seed for reproducibility. As in missMDA::imputePCA(), initialization i is seeded with seed * (i - 1). So seed = 0 gives every random initialization the same start, and nb.init then yields two distinct solves: the mean initialization and one random one. With nb.init > 1, seed can be at most .Machine$integer.max %/% (nb.init - 1).

row.w

Numeric vector, "n_miss", or NULL. The row weights, normalized to sum to 1: positive values of length nrow(obj), "n_miss" to down-weight rows with more missing values, or NULL for equal weights.

nb.init

Integer. Number of initializations. The first is always mean imputation, and the others are random.

maxiter

Integer. Maximum number of iterations.

miniter

Integer. Minimum number of iterations, at most maxiter.

solver

Character. One of "auto", "exact", or "lobpcg". The eigensolver. "auto" uses "exact" for small problems and otherwise runs a short timed probe, picking "lobpcg" only when it is clearly faster. With nb.init > 1, the choice from the first initialization is reused. See the PCA Performance tips section.

lobpcg_control

A list or NULL. LOBPCG control options, from lobpcg_control() or as a plain named list, or NULL for the defaults. Ignored when solver = "exact".

clamp

Numeric vector of length 2 or NULL. The bounds c(lower, upper) for PCA-imputed values, such as c(0, 1) for DNA methylation beta values, or NULL for none. Use -Inf or Inf for a one-sided bound. Observed values are not clamped.

method

Character or NULL. One of "euclidean" or "manhattan" for K-NN imputation, or "regularized" or "EM" for PCA imputation. NULL uses "euclidean" for K-NN and "regularized" for PCA.

.progress

Logical. If TRUE, show imputation progress.

colmax

Numeric scalar between 0 and 1. Columns with a proportion of missing values greater than colmax take no part in the imputation, as described under Column mean fill.

post_imp

Logical. If TRUE, column means replace the missing values that remain after imputation, as described under Column mean fill.

on_infeasible

Character. One of "skip", "error", or "mean". The action for a window that is infeasible for imputation, for example because k or ncp is too large for the columns that colmax leaves. Defaults to "skip".

Details

slide_imp() splits the columns of obj into windows by location and imputes each window on its own. There are two windowing modes:

Supply exactly one of k and ncp. k imputes each window with knn_imp(), and ncp imputes it with pca_imp(). The arguments of the other method are ignored.

The result holds the subset columns in the order they have in obj. In each window, every column the method can use takes part in the imputation, in subset or not: for K-NN every column within colmax, and for PCA every column within colmax whose variance is not zero. A name that is not in colnames(obj), or a subset that selects no column, is an error.

on_infeasible = "skip" does not impute an infeasible window, "mean" fills it with column means, and "error" stops at the first such window. With "skip" and "mean", slide_imp() raises one warning of class slideimp_fallback that lists the affected windows.

An infeasible window adds nothing to the mean_filled_cols and mean_filled_cells attributes. Where windows overlap, mean_filled_cells lists each cell that at least one window filled with its column mean.

With solver = "auto", the first window that completes the solver probe picks the solver, and every later window uses it.

slide_imp() rejects a column with no observed values only when a window covers it. A column that no window covers is returned unchanged.

Value

If dry_run = FALSE, a numeric matrix of class slideimp_results with the rows of obj and the columns that subset selects, with missing values imputed.

If dry_run = TRUE, a data frame of class slideimp_tbl with one row per window and the columns start and end (the first and last column of obj in the window), window_n, subset_local and, when flank = TRUE, target.

Column mean fill

A column with a proportion of missing values greater than colmax takes no part in the imputation. The method neither uses the column to impute other columns nor imputes it.

With post_imp = TRUE, column means replace the missing values that remain after the method has run. Two kinds of missing value can remain: the missing values of the columns that took no part, and the cells for which the method found no value. Each column mean is the mean of the column's observed values. With post_imp = FALSE, both kinds stay missing.

The result records what the column means replaced, in two attributes:

Both attributes are empty when no column mean was used. print() reports them when they are not empty.

Missing values and non-finite input

obj must be a double matrix. An integer or logical matrix is rejected, not converted. Convert one with storage.mode(obj) <- "double".

NA and NaN are both treated as missing. The package does not distinguish between them.

Inf and -Inf are rejected on entry, and so is a column with no observed values (every cell NA or NaN). Locate them with which(is.infinite(obj), arr.ind = TRUE) and which(colSums(!is.na(obj)) == 0).

PCA Performance tips

Three arguments set the speed: solver, threshold, and scale. Tune these first, then the accuracy arguments ncp and coeff.ridge, on a representative subset.

Exact vs. LOBPCG. "lobpcg" suits large, approximately low-rank matrices with small ncp. "exact" suits small matrices, such as slide_imp() windows, where it is faster. It is also more reliable: it always converges, to eigenvectors exact to machine precision, while LOBPCG stops at the tolerance set in lobpcg_control() and can take many iterations, or reach maxiter, when the eigenvalues around the ncp-th one are close together. The warm start makes each later LOBPCG solve cheap: pca_imp() starts LOBPCG from the previous eigenblock and search direction, so once the imputed values stabilize, each solve takes a few iterations. The gain grows with the number of EM iterations, whatever the rank. solver = "auto", the default, chooses between the two and is a safe start.

Threshold. The default 1e-6 is conservative. 1e-5 is often faster and gives very similar values.

Scale. For columns on a common scale, such as DNA methylation beta values in ⁠[0, 1]⁠, scale = FALSE can be faster and more accurate.

BLAS. On Windows, the BLAS that ships with R can be slow, and OpenBLAS can replace it.

See Speeding up PCA imputation for the full workflow.

Examples

set.seed(1234)

# Example data with 20 samples and 100 ordered columns
beta_matrix <- sim_mat(20, 100)$input
location <- 1:100

# First perform a dry run to inspect the calculated windows
window_statistics <- slide_imp(
  beta_matrix,
  location = location,
  window_size = 50,
  overlap_size = 10,
  min_window_n = 10,
  dry_run = TRUE,
  .progress = FALSE
)
window_statistics

# Sliding-window K-NN imputation
imputed_knn <- slide_imp(
  beta_matrix,
  location = location,
  k = 5,
  window_size = 50,
  overlap_size = 10,
  min_window_n = 10,
  .progress = FALSE
)
imputed_knn

# Sliding-window PCA imputation
imputed_pca <- slide_imp(
  beta_matrix,
  location = location,
  ncp = 2,
  window_size = 50,
  overlap_size = 10,
  min_window_n = 10,
  .progress = FALSE
)
imputed_pca

# K-NN imputation with flanking windows
imputed_flank <- slide_imp(
  beta_matrix,
  location = location,
  k = 2,
  window_size = 30,
  flank = TRUE,
  subset = c(10, 30, 70),
  min_window_n = 5,
  .progress = FALSE
)
imputed_flank


Resolution of a Group Specification

Description

Convert a group specification to the data frame that prep_groups() reads. This S3 generic is exported so that extension packages, such as slideimp.extra, can register methods for other classes.

Usage

slideimp_resolve_group(x)

## S3 method for class 'data.frame'
slideimp_resolve_group(x)

## Default S3 method:
slideimp_resolve_group(x)

Arguments

x

An object. The group specification: slideimp has a method for data.frame, and the optional slideimp.extra package adds one for a character platform name.

Value

A data frame. The data.frame method returns x with duplicate rows removed.

Examples

df <- data.frame(feature = c("cg1", "cg2"), group = c(1, 1))
slideimp_resolve_group(df)


Eigensolver Settings for Bayesian PCA Imputation

Description

Settings for the eigensolver that mipca(), mipca_tune(), mipca_fit() and mipca_flank() run at every iteration of the sampler. The defaults rarely need changing.

Usage

spectra_opts(tol = 1e-10, ncv = NULL, maxitr = 1000)

Arguments

tol

Numeric. Convergence tolerance of the eigenvalues, relative to their size. Defaults to 1e-10.

ncv

Integer or NULL. Number of Lanczos vectors the eigensolver keeps; more vectors converge in fewer iterations and use more memory. Defaults to NULL.

maxitr

Integer. Maximum number of eigensolver iterations at each iteration of the sampler. Defaults to 1000.

Details

The eigensolver is Spectra's. These settings change how it converges.

With ncv = NULL, ncv is 2 * rank + 3, at least 20 and at most the smaller dimension of obj once the abb columns are left out. A value given by hand must be more than rank + 1 and at most that dimension.

If a fit stops with "the PCA step did not converge", raise maxitr or ncv.

Value

A spectra_opts object, to pass as spectra.

See Also

mipca(), whose spectra argument this builds.

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)

# More Lanczos vectors and iterations than the defaults
opts <- spectra_opts(ncv = 15, maxitr = 5000)
fit <- mipca(sim$input, rank = 2, transform = "logit_biwhiten", spectra = opts, seed = 1)
fit

Summarize and Print a Bayesian PCA Imputation

Description

summary() returns Rhat and ESS for a sample of the missing values of a fit. print() shows a fit or a summary.

Usage

## S3 method for class 'si_mi_pca'
print(x, ...)

## S3 method for class 'si_mi'
print(x, ...)

## S3 method for class 'si_mi_pca'
summary(object, prop_diag = 0.5, ...)

## S3 method for class 'si_mi'
summary(object, ...)

## S3 method for class 'si_mi_summary'
print(x, n = 6L, ...)

Arguments

x

A si_mi, si_mi_pca or si_mi_summary object.

...

Not used.

object

A si_mi or si_mi_pca object. A fit from mipca() or mipca_fit().

prop_diag

Numeric scalar between 0 and 1. Proportion of each column's missing values on which Rhat and ESS are computed. 0 is refused. Only a resumable fit takes it. Defaults to 0.5.

n

Integer. Number of values with the highest Rhat to list. 0 lists none. Defaults to 6.

Details

Rhat and ESS. Rhat is the folded split Rhat of Vehtari et al. (2021). ESS is computed over all chains together. update() adds draws to a resumable fit, which raises ESS.

Which values. A column with h missing values gives ceiling(prop_diag * h) of them, spread evenly along the column. The sample is the same on every call. Columns listed in abb are left out.

Finalized and resumable fits. A finalized fit returns the values computed when it was finalized, with the prop_diag given to mipca() or mipca_finalize(). A resumable fit computes them on each call, with the prop_diag given here.

Short runs. Rhat is NA with fewer than 4 draws per chain, and ESS is NA with fewer than 12.

Joined fits. For fits joined with cbind(), chunk gives the fit each value comes from. print() shows mixed where the fits differ in prop_diag, chains or draws.

Printing. print() of a fit shows its size and the calls to make next. print() of a summary shows the number of values, the quantiles of rhat and ess, and the n values with the highest Rhat.

Value

References

Vehtari A, Gelman A, Simpson D, Carpenter B, Burkner P-C (2021). Rank-normalization, folding, and localization: an improved R-hat for assessing convergence of MCMC. Bayesian Analysis, 16(2), 667-718. doi:10.1214/20-BA1221

See Also

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)
fit <- mipca(sim$input, rank = 2, transform = "logit_biwhiten", seed = 1)
s <- summary(fit)
s
print(s, n = 3)
head(s$cells)

# A resumable fit takes prop_diag at each call
fit <- mipca(sim$input, rank = 2, transform = "logit_biwhiten", keep_state = TRUE, seed = 1)
summary(fit, prop_diag = 1)

Transforms for Bayesian PCA Imputation

Description

Transform obj prior to the Bayesian PCA imputation. Each draw is mapped back to the scale of obj before it is returned.

Usage

tf_identity()

tf_sv(n)

tf_biwhiten(base = tf_identity(), rows = TRUE)

Arguments

n

Integer. The sample size of the squeeze, usually nrow(obj). At least 2.

base

A transform object. The scale the rescaling is applied on: tf_identity(), tf_sv() or a transform of your own, not another tf_biwhiten(). Defaults to tf_identity().

rows

Logical. If TRUE, rescale the rows as well as the columns. Defaults to TRUE.

Details

The two names. transform = "identity" is tf_identity(), and transform = "logit_biwhiten" is tf_biwhiten(tf_sv(nrow(obj)), rows = TRUE). Build a transform with these functions to change one part of either, such as the logit without the rescaling, or the columns rescaled and the rows not.

tf_identity() fits the values as is.

tf_sv() is for proportions such as DNAm beta values. Each value y is squeezed to (y * (n - 1) + 0.5) / n, which moves 0 and 1 inside the interval (Smithson and Verkuilen, 2006), and then taken to the logit scale. Draws are mapped back and clamped to ⁠[0, 1]⁠. Every observed value must lie in ⁠[0, 1]⁠.

tf_biwhiten() rescales the columns, and with rows = TRUE the rows, of the matrix on the scale of base to a common noise level before the fit, and takes the scales back out of each draw. The scales are estimated once from the observed values, with the column variances shrunk as in Smyth (2004). The rescaling follows the idea of Landa, Zhang and Kluger (2022), with the scales estimated differently.

A transform of your own is a list with name, a string, and two functions, forward(y, ...) and backward(z, ...), where backward() undoes forward() value by value. Both must take ..., since the fit passes them column and row positions. It can be the base of tf_biwhiten().

Value

A transform object, to pass as transform.

References

Smithson M, Verkuilen J (2006). A better lemon squeezer? Maximum-likelihood regression with beta-distributed dependent variables. Psychological Methods, 11(1), 54-71. doi:10.1037/1082-989X.11.1.54

Smyth GK (2004). Linear models and empirical Bayes methods for assessing differential expression in microarray experiments. Statistical Applications in Genetics and Molecular Biology, 3(1), 1-25. doi:10.2202/1544-6115.1027

Landa B, Zhang TTCK, Kluger Y (2022). Biwhitening reveals the rank of a count matrix. SIAM Journal on Mathematics of Data Science, 4(4), 1420-1446. doi:10.1137/21M1456807

See Also

mipca(), whose transform argument these build.

Examples

set.seed(1)
sim <- sim_mat(n = 50, p = 20, beta = TRUE)
obj <- sim$input

# The same model as transform = "logit_biwhiten"
tf_logit_biwhiten <- tf_biwhiten(tf_sv(nrow(obj)), rows = TRUE)

# The logit without the rescaling
tf_logit <- tf_sv(nrow(obj))

# The columns rescaled, the rows not
tf_cols <- tf_biwhiten(tf_sv(nrow(obj)), rows = FALSE)
fit <- mipca(obj, rank = 2, transform = tf_cols, seed = 1)
fit

Hyperparameter Tuning for Imputation Methods

Description

Tune method-specific hyperparameters by repeatedly masking observed values, imputing them, and comparing the imputed values with the original values.

Usage

tune_imp(
  obj,
  parameters = NULL,
  .f,
  na_loc = NULL,
  num_na = NULL,
  n_reps = 1,
  n_cols = NULL,
  n_rows = 2,
  rowmax = 0.9,
  colmax = 0.9,
  na_col_subset = NULL,
  max_attempts = 100,
  .progress = TRUE,
  cores = 1,
  location = NULL,
  pin_blas = TRUE
)

Arguments

obj

A double matrix.

parameters

A data frame or NULL. One row per parameter set, one column per argument of .f other than obj. List-columns hold arguments that are not scalars. Duplicate rows are removed. NULL is allowed only for a custom .f, which is then called with its defaults.

.f

Character or function. One of "knn_imp", "pca_imp", or "slide_imp", or a custom imputation function, as described in Details.

na_loc

A matrix, numeric vector, list, or NULL. Positions to mask in place of sampled ones. A two-column matrix holds row and column indices, a numeric vector holds linear positions, and a list holds one of those per repetition.

num_na

Integer or NULL. Total number of missing values per repetition. When given, n_cols is ignored and the values are spread as evenly as possible over num_na %/% n_rows columns.

n_reps

Integer. Number of independent repetitions.

n_cols

Integer or NULL. Number of columns that receive missing values.

n_rows

Integer. Minimum number of missing values per selected column.

rowmax

Numeric scalar between 0 and 1. Maximum proportion of missing values per row after injection.

colmax

Numeric scalar between 0 and 1. Maximum proportion of missing values per column after injection.

na_col_subset

Optional character or integer vector. The columns that can receive missing values, by name or by number.

max_attempts

Integer. Maximum number of sampling attempts per repetition before an error.

.progress

Logical. If TRUE, show progress during tuning.

cores

Integer. Number of cores for K-NN imputation, including slide_imp() with k. For other methods, use mirai::daemons().

location

Numeric or NULL. The position of each column of obj, sorted in ascending order. .f = "slide_imp" needs it, and the other methods ignore it.

pin_blas

Logical. If TRUE, pin BLAS threads to 1 on the mirai daemons in a parallel run. Defaults to TRUE.

Details

A custom .f must accept obj as its first argument and return a numeric matrix with the same dimensions as obj and no Inf values. tune_imp() calls it once with the first parameter set before tuning starts, and stops if that call fails. After that, an iteration that fails or breaks this rule is recorded in the error column.

The columns of parameters for a custom function must not use the names of the columns that tune_imp() and compute_metrics() add: param_set, rep_id, result, error, n, n_miss, .metric, .estimator, and .estimate.

When mirai daemons are set, a custom function runs on the daemons. It finds the packages attached on the daemons, but not the variables of the session that defined it. Pass such values through parameters.

When mirai daemons are set, each daemon receives one copy of obj before tuning starts and keeps it until tuning ends. Each iteration masks cells in a second copy. Memory use therefore grows with the number of daemons.

When na_loc is supplied, num_na, n_reps, n_cols, n_rows, rowmax, colmax, na_col_subset, and max_attempts are ignored. The positions are not checked against rowmax or colmax.

When .f is a character string, columns in parameters are validated against the selected method:

To tune parameters for grouped imputation, tune knn_imp() or pca_imp() on representative groups, then pass the selected parameters to group_imp().

The top-level rowmax and colmax arguments control random missing-value injection performed by sample_na_loc(). To tune or pass an imputation method's own colmax argument, include a colmax column in parameters.

Tuning results can be summarized with compute_metrics() or evaluated with external packages such as yardstick.

Value

A data frame of class slideimp_tune with these columns:

Missing values and non-finite input

obj must be a double matrix. An integer or logical matrix is rejected, not converted. Convert one with storage.mode(obj) <- "double".

NA and NaN are both treated as missing. The package does not distinguish between them.

Inf and -Inf are rejected on entry, and so is a column with no observed values (every cell NA or NaN). Locate them with which(is.infinite(obj), arr.ind = TRUE) and which(colSums(!is.na(obj)) == 0).

Parallelization

PCA Performance tips

Three arguments set the speed: solver, threshold, and scale. Tune these first, then the accuracy arguments ncp and coeff.ridge, on a representative subset.

Exact vs. LOBPCG. "lobpcg" suits large, approximately low-rank matrices with small ncp. "exact" suits small matrices, such as slide_imp() windows, where it is faster. It is also more reliable: it always converges, to eigenvectors exact to machine precision, while LOBPCG stops at the tolerance set in lobpcg_control() and can take many iterations, or reach maxiter, when the eigenvalues around the ncp-th one are close together. The warm start makes each later LOBPCG solve cheap: pca_imp() starts LOBPCG from the previous eigenblock and search direction, so once the imputed values stabilize, each solve takes a few iterations. The gain grows with the number of EM iterations, whatever the rank. solver = "auto", the default, chooses between the two and is a safe start.

Threshold. The default 1e-6 is conservative. 1e-5 is often faster and gives very similar values.

Scale. For columns on a common scale, such as DNA methylation beta values in ⁠[0, 1]⁠, scale = FALSE can be faster and more accurate.

BLAS. On Windows, the BLAS that ships with R can be slow, and OpenBLAS can replace it.

See Speeding up PCA imputation for the full workflow.

See Also

sample_na_loc() to draw the na_loc locations in advance.

Examples

set.seed(123)

# Simulate some data
obj <- sim_mat(10, 50)$input

# Tune K-NN imputation with random missing-value injection.
# Use larger `num_na` and `n_reps` values for real analyses.
params_knn <- data.frame(k = c(2, 4))
results <- tune_imp(
  obj,
  params_knn,
  .f = "knn_imp",
  n_reps = 1,
  num_na = 10,
  .progress = FALSE
)
compute_metrics(results)

# Tune with fixed missing-value positions
na_positions <- list(
  matrix(c(1, 2, 3, 1, 1, 1), ncol = 2),
  matrix(c(2, 3, 4, 2, 2, 2), ncol = 2)
)

results_fixed <- tune_imp(
  obj,
  data.frame(k = 2),
  .f = "knn_imp",
  na_loc = na_positions,
  .progress = FALSE
)

# Custom imputation function
custom_fill <- function(obj, val = 0) {
  obj[is.na(obj)] <- val
  obj
}

tune_imp(
  obj,
  data.frame(val = c(0, 1)),
  .f = custom_fill,
  num_na = 10,
  .progress = FALSE
)


# Parallel tuning with mirai
mirai::daemons(2)

parameters_custom <- data.frame(mean = c(0, 1), sd = c(1, 1))

custom_imp <- function(obj, mean, sd) {
  na_pos <- is.na(obj)
  obj[na_pos] <- stats::rnorm(sum(na_pos), mean = mean, sd = sd)
  obj
}

results_p <- tune_imp(
  obj,
  parameters_custom,
  .f = custom_imp,
  n_reps = 1,
  num_na = 10,
  .progress = FALSE
)

mirai::daemons(0)

mirror server hosted at Truenetwork, Russian Federation.