| 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 |
| 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:
-
mean_filled_cols: an integer vector with the index, in the result, of each column that took no part and was filled. -
mean_filled_cells: an integer matrix with the columnsrowandcol, one row for each cell that the method could not impute and that was filled.
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:
Hung Pham amser.hoanghung@gmail.com (ORCID) [copyright holder]
Other contributors:
Francois Husson (ORCID) ('missMDA' imputePCA() and MIPCA(), reimplemented in R/pca_imp.R, src/pca_kernel.cpp, R/mi_pca_imp.R and src/mipca.cpp) [contributor, copyright holder]
Julie Josse (ORCID) ('missMDA' imputePCA() and MIPCA(), reimplemented in R/pca_imp.R, src/pca_kernel.cpp, R/mi_pca_imp.R and src/mipca.cpp) [contributor, copyright holder]
Vincent Audigier ('missMDA' MIPCA() Bayesian sampler, reimplemented in R/mi_pca_imp.R and src/mipca.cpp) [contributor, copyright holder]
Posit Software, PBC ('carrier' package code, adapted in R/crate.R and tests/testthat/test-crate*.R) [copyright holder]
Yixuan Qiu (Spectra library, vendored in src/Spectra) [contributor, copyright holder]
Gael Guennebaud (Eigen SelfAdjointEigenSolver code, adapted in src/Spectra/LinAlg/TridiagEigen.h) [contributor, copyright holder]
Jitse Niesen (Eigen SelfAdjointEigenSolver code, adapted in src/Spectra/LinAlg/TridiagEigen.h) [contributor, copyright holder]
See Also
Useful links:
Report bugs at https://github.com/hhp94/slideimp/issues
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 |
bound |
Numeric. A value below |
q |
Numeric. Proportion of a column's observed values that must be near
|
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
-
mipca()to fit with the list. -
mipca_flank_plan(), which leaves the listed columns out of every window.
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 |
... |
Not used. |
draw |
Integer. The kept draw that fills the missing values, from |
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
-
mipca()to make a finalized fit. -
mipca_finalize()to finalize a resumable fit.
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 |
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
-
mipca()to fit each part. -
as.matrix()andsummary(), which take the joined fit as any other.
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 |
metrics |
Character. The metrics to compute, any of |
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.
-
"mae": mean absolute error. -
"rmse": root mean squared error. -
"mape": mean absolute percentage error, in percent. It divides by the true value, so it is not finite (InforNaN) for a repetition in which a masked value is exactly0. Use another metric for data that contain zeros. -
"bias": mean of the estimate minus the true value. -
"rsq": squared Pearson correlation of the estimates and the true values. It isNAwhen either is constant or fewer than two values have an estimate. -
"rsq_trad": one minus the residual sum of squares over the total sum of squares. It isNAwhen the true values are constant or fewer than two values have an estimate.
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:
|
subset |
Optional character vector. The features to impute and
return, by name, or |
allow_unmapped |
Logical. If |
k |
Integer or |
ncp |
Integer or |
method |
Character or |
cores |
Integer. Number of cores for K-NN imputation only, as described under Parallelization. |
.progress |
Logical. If |
min_group_size |
Integer or |
colmax |
Numeric scalar between |
post_imp |
Logical. If |
dist_pow |
Numeric. Power used to penalize more distant neighbors in
the weighted average, where |
scale |
Logical. If |
coeff.ridge |
Numeric. The ridge regularization for
|
threshold |
Numeric. Convergence threshold. |
row.w |
Numeric vector, |
seed |
Integer, numeric, or |
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 |
solver |
Character. One of |
lobpcg_control |
A list or |
clamp |
Numeric vector of length 2 or |
pin_blas |
Logical. If |
on_infeasible |
Character. One of |
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
K-NN: use the
coresargument. Ifmiraidaemons are active,coresis set to1to avoid nested parallelism.PCA: use
mirai::daemons()instead ofcores.With
miraidaemons, each daemon runs BLAS on one thread unlesspin_blas = FALSE.
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:
-
mean_filled_cols: an integer vector with the index, in the result, of each column that took no part and was filled. -
mean_filled_cells: an integer matrix with the columnsrowandcol, one row for each cell that the method could not impute and that was filled.
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
-
prep_groups()to inspect and edit the groups and their parameters.
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 |
method |
Character. One of |
cores |
Integer. Number of cores for K-NN imputation. Defaults to |
post_imp |
Logical. If |
subset |
Optional character or integer vector. The columns to impute
and return, by name or by number, or |
dist_pow |
Numeric. Power used to penalize more distant neighbors in
the weighted average, where |
.progress |
Logical. If |
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
Use
subsetwhen only specific columns need imputation.Use
group_imp()orslide_imp()for very large matrices.
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:
-
mean_filled_cols: an integer vector with the index, in the result, of each column that took no part and was filled. -
mean_filled_cells: an integer matrix with the columnsrowandcol, one row for each cell that the method could not impute and that was filled.
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 |
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 |
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 ( |
prop |
Logical. Whether to return missing-value proportions ( |
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. |
rank |
Integer. Number of principal components in the model. Use
|
transform |
Character or a transform object. The scale the model is
fitted on: |
subset |
Optional character or integer vector. The columns whose draws
are kept and returned, by name or by number, or |
keep_state |
Logical. If |
prop_diag |
Numeric scalar between |
iter_sampling |
Integer. Number of draws kept per chain. Defaults to
|
iter_warmup |
Integer. Number of iterations discarded at the start of
each chain, |
thin |
Integer. After warmup, each chain keeps one iteration in every
|
nu |
Numeric. Degrees of freedom of the noise drawn for a missing value:
|
chains |
Integer. Number of independent chains. Defaults to |
refresh |
Integer. Print a progress line every |
spectra |
A |
init |
Numeric. How widely each chain's starting values are spread: each
missing value starts at a random draw whose standard deviation is |
seed |
Integer, numeric, or |
abb |
Optional character or integer vector. Columns to draw by
approximate Bayesian bootstrap instead of by the model. |
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:
-
as.matrix(fit, draw = b)for the completed matrix at drawb. -
summary()for Rhat and ESS. -
cbind()to join fits made over different columns.
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
-
mipca_tune()andmipca_fit()to chooserankandnuon held-out values, then fit. -
mipca_flank_plan()to fit each target column on a window of its neighbors by location. -
pca_imp()for a single imputation.
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 |
iter_sampling |
Integer. Number of draws to add to each chain. |
... |
Not used. |
x |
A |
thin |
Integer. Keep every |
prop_diag |
Numeric scalar between |
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
-
update():object, invisibly, extended in place. -
mipca_finalize(): a finalized fit of classsi_mi, asmipca()returns withkeep_state = FALSE.
See Also
-
mipca()to make a resumable fit withkeep_state = TRUE. -
as.matrix()for the completed matrices of the finalized fit.
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 |
obj |
A double matrix. The matrix |
rank |
Integer or |
... |
Not used. Name every argument after |
chains |
Integer. Number of independent chains. Taken from |
iter_warmup |
Integer. Number of iterations discarded at the start of
each chain, |
iter_sampling |
Integer. Number of draws kept per chain. Taken from
|
thin |
Integer. After warmup, each chain keeps one iteration in every
|
spectra |
A |
init |
Numeric. How widely each chain's starting values are spread, as
in |
refresh |
Integer. Print a progress line every |
keep_state |
Logical. If |
prop_diag |
Numeric scalar between |
seed |
Integer, numeric, or |
nu |
Numeric or |
transform, abb |
Not used. The fit uses the transform and |
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
-
mipca_tune()to make the table. -
mipca()to fit with a rank andnuof your own.
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. |
location |
Numeric. The position of each column of |
window_size |
Numeric. Distance from the target, in the units of
|
subset |
Character or integer vector. In |
min_window_n |
Integer. Minimum number of columns in a window, the
target included, at least |
colmax |
Numeric scalar between |
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. |
x |
A |
n |
Integer. Number of rows of the table to print. Defaults to |
... |
Not used. |
plan |
A |
rank |
Integer. Number of principal components in the model. Use
|
seed |
Integer. Seed for the sampler. |
transform |
Character or a transform object. The scale the model is
fitted on: |
prop_diag |
Numeric scalar between |
iter_sampling |
Integer. Number of draws kept per chain. Defaults to
|
iter_warmup |
Integer. Number of iterations discarded at the start of
each chain, |
thin |
Integer. After warmup, each chain keeps one iteration in every
|
nu |
Numeric. Degrees of freedom of the noise drawn for a missing value:
|
chains |
Integer. Number of independent chains. Defaults to |
spectra |
A |
init |
Numeric. How widely each chain's starting values are spread: each
missing value starts at a random draw whose standard deviation is |
.progress |
Logical. If |
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:
-
"impute": fitted on its window. -
"clean": no missing values. -
"abb": listed inabb, and drawn from its own observed values. -
"inadmissible": constant, with fewer than two observed values, or missing more thancolmax. Its missing values stayNA. -
"window_small": fewer thanmin_window_ncolumns in its window. Its missing values stayNA.
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
-
mipca_flank_plan(): asi_flank_planobject, holdingobj, the settings and the tabletargets. -
mipca_flank(): a finalized fit of classsi_miover the targets, asmipca()returns. -
mipca_flank_window(): a numeric matrix, the columns of the target's window. -
print():x, invisibly.
See Also
-
mipca()to fit the whole matrix at once. -
mipca_tune()to choose the rank on a window. -
cbind()to join the fits of several matrices, such as one per chromosome.
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. |
rank |
Integer vector. The candidate ranks, each a whole number of at
least |
na_loc |
A list or |
n_cols |
Integer or |
n_rows |
Integer. Number of held-out values in each of the |
transform |
Character or a transform object. The scale the model is
fitted on: |
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 |
iter_warmup |
Integer. Number of iterations discarded at the start of
each chain, |
iter_sampling |
Integer. Number of draws kept per chain. Defaults to
|
chains |
Integer. Number of independent chains. Defaults to |
thin |
Integer. After warmup, each chain keeps one iteration in every
|
init |
Numeric. How widely each chain's starting values are spread: each
missing value starts at a random draw whose standard deviation is |
refresh |
Integer. Print a progress line every |
spectra |
A |
seed |
Integer, numeric, or |
abb |
Optional character or integer vector. Columns to draw by
approximate Bayesian bootstrap instead of by the model. |
x |
A |
... |
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:
-
rank: the rank. -
crps: the mean score of the held-out values. Lower is better. -
implied_nu,implied_lo,implied_hi: the degrees of freedom the held-out values imply, and its 68% bootstrap interval. -
robust_z: the interquartile range of the standardized held-out values, divided by1.349. Near1for Gaussian noise. -
ess_min,ess_p10,ess_med: the minimum, 10% quantile and median ESS over then_diagvalues. -
ess_ok: the proportion of them with an ESS of at least100 * chains. -
rhat_med,rhat_p90,rhat_max: the median, 90% quantile and maximum Rhat. -
rhat_ok: the proportion with an Rhat of at most1.05. -
ndraws: the number of draws, over all chains. -
n_diag: the number of values Rhat and ESS were computed on. -
sigma: a list column, the noise standard deviation at the end of each chain. -
time: the seconds the rank took. -
error: the message of a failed fit, orNA. -
result: a list column, a data frame with one row per held-out value: itsrowandcol, thetruth, themeanandsdof its draws, itscrpsandpit, andtruth_lat,mean_latandsd_laton the scale the model is fitted on. -
diag: a list column, a data frame of therow,col,rhatandessof each of then_diagvalues.
The table also carries the transform, the sampler settings, abb and the
held-out positions, which mipca_fit() reads.
See Also
-
mipca_fit()to fit a rank from this table. -
mipca()to fit with a rank andnuof your own. -
sample_na_loc()to draw held-out positions to pass asna_loc.
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 |
method |
Character. One of |
coeff.ridge |
Numeric. The ridge regularization for
|
row.w |
Numeric vector, |
threshold |
Numeric. Convergence threshold. |
seed |
Integer, numeric, or |
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 |
solver |
Character. One of |
lobpcg_control |
A list or |
colmax |
Numeric scalar between |
post_imp |
Logical. If |
clamp |
Numeric vector of length 2 or |
subset |
Optional character or integer vector. The columns to impute
and return, by name or by number, or |
.progress |
Logical. If |
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:
-
mean_filled_cols: an integer vector with the index, in the result, of each column that took no part and was filled. -
mean_filled_cells: an integer matrix with the columnsrowandcol, one row for each cell that the method could not impute and that was filled.
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
-
group_imp()to impute within feature groups. -
mipca()for multiple imputation with PCA.
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 |
group |
A data frame or a character scalar. The feature groups, in one of these forms:
|
subset |
Optional character vector. The features to impute, by name,
or |
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
|
allow_unmapped |
Logical. If |
seed |
Integer, numeric, or |
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:
-
group: original group labels, if provided, or sequential group labels. -
feature: a list-column of character vectors containing feature names. -
aux: a list-column of character vectors containing auxiliary names. -
parameters: a list-column of per-group configuration lists.
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 |
n |
Integer. Number of rows to print. |
p |
Integer. Number of columns to print. |
... |
Further arguments passed to |
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 |
n |
Integer. Number of rows of each component to show. |
p |
Integer. Number of columns of |
... |
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 |
n |
Integer or |
... |
Further arguments passed to |
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 |
n_rows |
Integer. Minimum number of missing values per selected column. |
num_na |
Integer or |
n_reps |
Integer. Number of independent repetitions. |
rowmax |
Numeric scalar between |
colmax |
Numeric scalar between |
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:
The proportion of missing values in each row and column, existing ones included, stays at or under
rowmaxandcolmax.Every selected column keeps at least two distinct observed values.
A column with a variance below
.Machine$double.epscounts as constant and is never selected.pca_imp()uses the same threshold to leave a column out of its fit.
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
-
tune_imp(), which takes the result asna_loc. -
mipca_tune(), which takes a result withn_reps = 1asna_loc.
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 |
p |
Integer. Number of columns, interpreted as features. Defaults to
|
rho |
Numeric. Correlation between every pair of columns before
scaling, at least |
n_col_groups |
Integer. Number of group labels drawn at random for
the features. Defaults to |
n_row_groups |
Integer. Number of group labels drawn at random for
the samples. Defaults to |
perc_total_na |
Numeric scalar between |
perc_col_na |
Numeric scalar between |
beta |
Logical. If |
Value
A slideimp_sim object, a list with:
-
input: a numeric matrix of dimensionn \times pthat holds the simulated values and the injectedNAvalues. -
col_group: a data frame withprows mapping eachfeatureto agroup. -
row_group: a data frame withnrows mapping eachsampleto agroup. -
n_col_groups,n_row_groups: the group counts as given.
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 |
window_size |
Numeric. The width of each window, in the units of
|
overlap_size |
Numeric. The overlap between consecutive windows, in the
units of |
flank |
Logical. If |
min_window_n |
Integer. The smallest number of columns, at least |
subset |
Optional character or integer vector. The columns to impute
and return, by name or by number, or |
dry_run |
Logical. If |
k |
Integer or |
cores |
Integer. Number of cores for K-NN imputation. Defaults to |
dist_pow |
Numeric. Power used to penalize more distant neighbors in
the weighted average, where |
ncp |
Integer or |
scale |
Logical. If |
coeff.ridge |
Numeric. The ridge regularization for
|
threshold |
Numeric. Convergence threshold. |
seed |
Integer, numeric, or |
row.w |
Numeric vector, |
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 |
solver |
Character. One of |
lobpcg_control |
A list or |
clamp |
Numeric vector of length 2 or |
method |
Character or |
.progress |
Logical. If |
colmax |
Numeric scalar between |
post_imp |
Logical. If |
on_infeasible |
Character. One of |
Details
slide_imp() splits the columns of obj into windows by location and
imputes each window on its own. There are two windowing modes:
-
flank = FALSE: greedily partitionlocationinto windows of widthwindow_sizewith the requestedoverlap_sizebetween consecutive windows. A window that would add no column to the window before it is not created. A column in more than one window takes the mean of their imputed values. -
flank = TRUE: create one window per feature insubset. Each window covers thelocationvalues withinwindow_sizeof that feature, on both sides, so it spans twicewindow_size.
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:
-
mean_filled_cols: an integer vector with the index, in the result, of each column that took no part and was filled. -
mean_filled_cells: an integer matrix with the columnsrowandcol, one row for each cell that the method could not impute and that was filled.
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: |
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 |
ncv |
Integer or |
maxitr |
Integer. Maximum number of eigensolver iterations at each
iteration of the sampler. Defaults to |
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 |
... |
Not used. |
object |
A |
prop_diag |
Numeric scalar between |
n |
Integer. Number of values with the highest Rhat to list. |
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
-
summary(): an object of classsi_mi_summary. Its attributesprop_diag,nchainsandndrawshold the proportion, the number of chains and the draws per chain, orNAwhere joined fits differ. Its elementcellsis a data frame with one row per value, in column order:-
chunk: the fit the value comes from,1unless fits were joined withcbind(). Finalized fits only. -
col,name: the column number and name in the completed matrix. -
row: the row number. -
rhat,ess: Rhat and ESS.
-
-
print():x, invisibly.
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 |
base |
A transform object. The scale the rescaling is applied on:
|
rows |
Logical. If |
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 |
.f |
Character or function. One of |
na_loc |
A matrix, numeric vector, list, or |
num_na |
Integer or |
n_reps |
Integer. Number of independent repetitions. |
n_cols |
Integer or |
n_rows |
Integer. Minimum number of missing values per selected column. |
rowmax |
Numeric scalar between |
colmax |
Numeric scalar between |
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 |
cores |
Integer. Number of cores for K-NN imputation, including
|
location |
Numeric or |
pin_blas |
Logical. If |
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:
-
"knn_imp"requiresk. -
"pca_imp"requiresncp. -
"slide_imp"requireswindow_size,overlap_size, andmin_window_n, plus exactly one ofkorncp.
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:
the columns of
parameters.-
param_set, an integer ID for each unique parameter combination. -
rep_id, an integer repetition index. -
result, a list-column of data frames, each withtruthandestimatecolumns. -
error, a character column with the error message of a failed iteration, orNA.
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
K-NN: use the
coresargument. Ifmiraidaemons are active,coresis set to1to avoid nested parallelism.PCA: use
mirai::daemons()instead ofcores.With
miraidaemons, each daemon runs BLAS on one thread unlesspin_blas = FALSE.
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)