| Title: | Visualization and Imputation of Missing Values |
|---|---|
| Description: | Provides methods for imputation and visualization of missing values. It includes graphical tools to explore the amount, structure and patterns of missing and/or imputed values, supporting exploratory data analysis and helping to investigate potential missingness mechanisms (details in Alfons, Templ and Filzmoser, <doi:10.1007/s11634-011-0102-y>). The quality of imputations can be assessed visually using a wide range of univariate, bivariate and multivariate plots. The package further provides several imputation methods, including efficient implementations of k-nearest neighbour and hot-deck imputation (Kowarik and Templ 2013, <doi:10.18637/jss.v074.i07>), iterative robust model-based multiple imputation (Templ 2011, <doi:10.1016/j.csda.2011.04.012>; Templ 2023, <doi:10.3390/math11122729>), and machine learning–based approaches such as robust GAM-based multiple imputation (Templ 2024, <doi:10.1007/s11222-024-10429-1>) as well as random forest and gradient boosting (XGBoost) imputation (Niederhametner et al., <doi:10.1177/18747655251339401>). General background and practical guidance on imputation are provided in the Springer book by Templ (2023) <doi:10.1007/978-3-031-30073-8>. |
| Authors: | Matthias Templ [aut, cre], Alexander Kowarik [aut] (ORCID: <https://orcid.org/0000-0001-8598-4130>), Andreas Alfons [aut], Johannes Gussenbauer [aut], Nina Niederhametner [aut], Eileen Vattheuer [aut], Gregor de Cillia [aut], Bernd Prantner [ctb], Wolfgang Rannetbauer [aut] |
| Maintainer: | Matthias Templ <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 7.5.1 |
| Built: | 2026-09-22 15:16:50 UTC |
| Source: | https://github.com/statistikat/vim |
Calculate or plot the amount of missing/imputed values in each variable and the amount of missing/imputed values in certain combinations of variables.
Print method for objects of class "aggr".
Summary method for objects of class "aggr".
Print method for objects of class "summary.aggr".
aggr(x, delimiter = NULL, plot = TRUE, ...) ## S3 method for class 'aggr' plot( x, col = c("skyblue", "red", "orange"), bars = TRUE, numbers = FALSE, prop = TRUE, combined = FALSE, varheight = FALSE, only.miss = FALSE, border = par("fg"), sortVars = FALSE, sortCombs = TRUE, ylabs = NULL, axes = TRUE, labels = axes, cex.lab = 1.2, cex.axis = par("cex"), cex.numbers = par("cex"), gap = 4, ... ) ## S3 method for class 'aggr' print(x, ..., digits = NULL) ## S3 method for class 'aggr' summary(object, ...) ## S3 method for class 'summary.aggr' print(x, ...)aggr(x, delimiter = NULL, plot = TRUE, ...) ## S3 method for class 'aggr' plot( x, col = c("skyblue", "red", "orange"), bars = TRUE, numbers = FALSE, prop = TRUE, combined = FALSE, varheight = FALSE, only.miss = FALSE, border = par("fg"), sortVars = FALSE, sortCombs = TRUE, ylabs = NULL, axes = TRUE, labels = axes, cex.lab = 1.2, cex.axis = par("cex"), cex.numbers = par("cex"), gap = 4, ... ) ## S3 method for class 'aggr' print(x, ..., digits = NULL) ## S3 method for class 'aggr' summary(object, ...) ## S3 method for class 'summary.aggr' print(x, ...)
x |
an object of class |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
plot |
a logical indicating whether the results should be plotted (the
default is |
... |
Further arguments, currently ignored. |
col |
a vector of length three giving the colors to be used for observed, missing and imputed data. If only one color is supplied, it is used for missing and imputed data and observed data is transparent. If only two colors are supplied, the first one is used for observed data and the second color is used for missing and imputed data. |
bars |
a logical indicating whether a small barplot for the frequencies of the different combinations should be drawn. |
numbers |
a logical indicating whether the proportion or frequencies of the different combinations should be represented by numbers. |
prop |
a logical indicating whether the proportion of missing/imputed values and combinations should be used rather than the total amount. |
combined |
a logical indicating whether the two plots should be
combined. If |
varheight |
a logical indicating whether the cell heights are given by the frequencies of occurrence of the corresponding combinations. |
only.miss |
a logical indicating whether the small barplot for the
frequencies of the combinations should only be drawn for combinations
including missing/imputed values (if |
border |
the color to be used for the border of the bars and
rectangles. Use |
sortVars |
a logical indicating whether the variables should be sorted by the number of missing/imputed values. |
sortCombs |
a logical indicating whether the combinations should be sorted by the frequency of occurrence. |
ylabs |
if |
axes |
a logical indicating whether axes should be drawn. |
labels |
either a logical indicating whether labels should be plotted on the x-axis, or a character vector giving the labels. |
cex.lab |
the character expansion factor to be used for the axis labels. |
cex.axis |
the character expansion factor to be used for the axis annotation. |
cex.numbers |
the character expansion factor to be used for the proportion or frequencies of the different combinations |
gap |
if |
digits |
the minimum number of significant digits to be used (see
|
object |
an object of class |
Often it is of interest how many missing/imputed values are contained in each variable. Even more interesting, there may be certain combinations of variables with a high number of missing/imputed values.
If combined is FALSE, two separate plots are drawn for the
missing/imputed values in each variable and the combinations of
missing/imputed and non-missing values. The barplot on the left hand side
shows the amount of missing/imputed values in each variable. In the
aggregation plot on the right hand side, all existing combinations of
missing/imputed and non-missing values in the observations are visualized.
Available, missing and imputed data are color coded as given by col.
Additionally, there are two possibilities to represent the frequencies of
occurrence of the different combinations. The first option is to visualize
the proportions or frequencies by a small bar plot and/or numbers. The
second option is to let the cell heights be given by the frequencies of the
corresponding combinations. Furthermore, variables may be sorted by the
number of missing/imputed values and combinations by the frequency of
occurrence to give more power to finding the structure of missing/imputed
values.
If combined is TRUE, a small version of the barplot showing
the amount of missing/imputed values in each variable is drawn on top of the
aggregation plot.
The graphical parameter oma will be set unless supplied as an
argument.
for aggr, a list of class "aggr" containing the
following components:
x the data used.
combinations a character vector representing the combinations of variables.
count the frequencies of these combinations.
percent the percentage of these combinations.
missings a data.frame containing the amount of
missing/imputed values in each variable.
tabcomb the indicator matrix for the combinations of variables.
a list of class "summary.aggr" containing the following
components:
missings a data.frame containing the amount of missing or
imputed values in each variable.
combinations a data.frame containing a character vector
representing the combinations of variables along with their frequencies and
percentages.
Some of the argument names and positions have changed with version 1.3
due to extended functionality and for more consistency with other plot
functions in VIM. For back compatibility, the arguments labs
and names.arg can still be supplied to ...{} and are handled
correctly. Nevertheless, they are deprecated and no longer documented. Use
ylabs and labels instead.
Andreas Alfons, Matthias Templ, modifications for displaying imputed values by Bernd Prantner
Matthias Templ, modifications by Andreas Alfons and Bernd Prantner
Matthias Templ, modifications by Andreas Alfons
Andreas Alfons, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(sleep, package="VIM") ## for missing values a <- aggr(sleep) a summary(a) ## for imputed values sleep_IMPUTED <- kNN(sleep) a <- aggr(sleep_IMPUTED, delimiter="_imp") a summary(a) data(sleep, package = "VIM") a <- aggr(sleep, plot=FALSE) a data(sleep, package = "VIM") summary(aggr(sleep, plot=FALSE)) data(sleep, package = "VIM") s <- summary(aggr(sleep, plot=FALSE)) sdata(sleep, package="VIM") ## for missing values a <- aggr(sleep) a summary(a) ## for imputed values sleep_IMPUTED <- kNN(sleep) a <- aggr(sleep_IMPUTED, delimiter="_imp") a summary(a) data(sleep, package = "VIM") a <- aggr(sleep, plot=FALSE) a data(sleep, package = "VIM") summary(aggr(sleep, plot=FALSE)) data(sleep, package = "VIM") s <- summary(aggr(sleep, plot=FALSE)) s
Convert colors to semitransparent colors.
alphablend(col, alpha = NULL, bg = NULL)alphablend(col, alpha = NULL, bg = NULL)
col |
a vector specifying colors. |
alpha |
a numeric vector containing the alpha values (between 0 and 1). |
bg |
the background color to be used for alphablending. This can be used as a workaround for graphics devices that do not support semitransparent colors. |
a vector containing the semitransparent colors.
Andreas Alfons
alphablend("red", 0.6)alphablend("red", 0.6)
Average log brain and log body weights for 28 Species
A data frame with 28 observations on the following 2 variables.
log body weight
log brain weight
The original data can be found in package MASS. 10 values on brain weight are set to be missing.
P. J. Rousseeuw and A. M. Leroy (1987) Robust Regression and Outlier Detection. Wiley, p. 57.
Venables, W. N. and Ripley, B. D. (1999) Modern Applied Statistics with S-PLUS. Third Edition. Springer.
Templ, M. (2022) Visualization and Imputation of Missing Values. Springer Publishing. Upcoming book.
data(Animals_na) aggr(Animals_na)data(Animals_na) aggr(Animals_na)
Barplot with highlighting of missing/imputed values in other variables by splitting each bar into two parts. Additionally, information about missing/imputed values in the variable of interest is shown on the right hand side.
barMiss( x, delimiter = NULL, pos = 1, selection = c("any", "all"), col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), border = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, labels = axes, only.miss = TRUE, miss.labels = axes, interactive = TRUE, ... )barMiss( x, delimiter = NULL, pos = 1, selection = c("any", "all"), col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), border = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, labels = axes, only.miss = TRUE, miss.labels = axes, interactive = TRUE, ... )
x |
a vector, matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
pos |
a numeric value giving the index of the variable of interest.
Additional variables in |
selection |
the selection method for highlighting missing/imputed
values in multiple additional variables. Possible values are |
col |
a vector of length six giving the colors to be used. If only one color is supplied, the bars are transparent and the supplied color is used for highlighting missing/imputed values. Else if two colors are supplied, they are recycled. |
border |
the color to be used for the border of the bars. Use
|
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
axes |
a logical indicating whether axes should be drawn on the plot. |
labels |
either a logical indicating whether labels should be plotted below each bar, or a character vector giving the labels. |
only.miss |
logical; if |
miss.labels |
either a logical indicating whether label(s) should be plotted below the bar(s) on the right hand side, or a character string or vector giving the label(s) (see ‘Details’). |
interactive |
a logical indicating whether variables can be switched interactively (see ‘Details’). |
... |
further graphical parameters to be passed to
|
If more than one variable is supplied, the bars for the variable of interest are split according to missingness/number of imputed missings in the additional variables.
If only.miss=TRUE, the missing/imputed values in the variable of
interest are visualized by one bar on the right hand side. If additional
variables are supplied, this bar is again split into two parts according to
missingness/number of imputed missings in the additional variables.
Otherwise, a small barplot consisting of two bars is drawn on the right hand
side. The first bar corresponds to observed values in the variable of
interest and the second bar to missing/imputed values. Since these two bars
are not on the same scale as the main barplot, a second y-axis is plotted on
the right (if axes=TRUE). Each of the two bars are again split into
two parts according to missingness/number of imputed missings in the
additional variables. Note that this display does not make sense if only
one variable is supplied, therefore only.miss is ignored in that
case.
If interactive=TRUE, clicking in the left margin of the plot results
in switching to the previous variable and clicking in the right margin
results in switching to the next variable. Clicking anywhere else on the
graphics device quits the interactive session. When switching to a
continuous variable, a histogram is plotted rather than a barplot.
a numeric vector giving the coordinates of the midpoints of the bars.
Some of the argument names and positions have changed with version 1.3
due to extended functionality and for more consistency with other plot
functions in VIM. For back compatibility, the arguments
axisnames, names.arg and names.miss can still be
supplied to ...{} and are handled correctly. Nevertheless, they
are deprecated and no longer documented. Use labels and
miss.labels instead.
Andreas Alfons, modifications to show imputed values by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(sleep, package = "VIM") ## for missing values x <- sleep[, c("Exp", "Sleep")] barMiss(x) barMiss(x, only.miss = FALSE) ## for imputed values x_IMPUTED <- kNN(sleep[, c("Exp", "Sleep")]) barMiss(x_IMPUTED, delimiter = "_imp") barMiss(x_IMPUTED, delimiter = "_imp", only.miss = FALSE)data(sleep, package = "VIM") ## for missing values x <- sleep[, c("Exp", "Sleep")] barMiss(x) barMiss(x, only.miss = FALSE) ## for imputed values x_IMPUTED <- kNN(sleep[, c("Exp", "Sleep")]) barMiss(x_IMPUTED, delimiter = "_imp") barMiss(x_IMPUTED, delimiter = "_imp", only.miss = FALSE)
Dataset containing the original Wisconsin breast cancer data.
A data frame with 699 observations on the following 11 variables.
Sample ID
as integer from 1 - 10
as integer from 1 - 10
as integer from 1 - 10
as integer from 1 - 10
as integer from 1 - 10
as integer from 1 - 10, includes 16 missings
as integer from 1 - 10
as integer from 1 - 10
as integer from 1 - 10
benign or malignant
The data downloaded and conditioned for R from the UCI machine learning repository, see https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+(Original) This breast cancer databases was obtained from the University of Wisconsin Hospitals, Madison from Dr. William H. Wolberg. If you publish results when using this database, then please include this information in your acknowledgements. Also, please cite one or more of: O. L. Mangasarian and W. H. Wolberg: "Cancer diagnosis via linear programming", SIAM News, Volume 23, Number 5, September 1990, pp 1 & 18. William H. Wolberg and O.L. Mangasarian: "Multisurface method of pattern separation for medical diagnosis applied to breast cytology", Proceedings of the National Academy of Sciences, U.S.A., Volume 87, December 1990, pp 9193-9196. O. L. Mangasarian, R. Setiono, and W.H. Wolberg: "Pattern recognition via linear programming: Theory and application to medical diagnosis", in: "Large-scale numerical optimization", Thomas F. Coleman and Yuying Li, editors, SIAM Publications, Philadelphia 1990, pp 22-30. K. P. Bennett & O. L. Mangasarian: "Robust linear programming discrimination of two linearly inseparable sets", Optimization Methods and Software 1, 1992, 23-34 (Gordon & Breach Science Publishers).
data(bcancer) aggr(bcancer)data(bcancer) aggr(bcancer)
Plot a background map.
bgmap(map, add = FALSE, ...)bgmap(map, add = FALSE, ...)
map |
either a matrix or |
add |
a logical indicating whether |
... |
further arguments and graphical parameters to be passed to
|
Andreas Alfons
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Vol. 6, pp. 29-47. DOI: 10.1007/s11634-011-0102-y.
data(kola.background, package = "VIM") bgmap(kola.background)data(kola.background, package = "VIM") bgmap(kola.background)
A plastic product is produced in three parallel reactors (TK104, TK105, or TK107). For each row in the dataset, we have the same batch of raw material that was split, and fed to the 3 reactors. These values are the brittleness index for the product produced in the reactor. A simulated data set.
A data frame with 23 observations on the following 3 variables.
Brittleness for batches of raw material in reactor 104
Brittleness for batches of raw material in reactor 105
Brittleness for batches of raw material in reactor 107
https://openmv.net/info/brittleness-index
data(brittleness) aggr(brittleness)data(brittleness) aggr(brittleness)
For each continuous cell (i,j), computes the conditional expectation
under a robust Gaussian model (estimated via MCD),
standardizes the residual, and applies a weight function. This captures
multivariate outlier structure that univariate standardization misses.
cellWeightsMCD(X, method = "tukey", alpha = NULL)cellWeightsMCD(X, method = "tukey", alpha = NULL)
X |
a data frame or matrix of dimension n x p (continuous columns only) |
method |
weight function: |
alpha |
tuning constant. If |
an n x p numeric matrix of weights in
Matthias Templ
This data set is the same as
in package mvoutlier, except that values below the detection limit
are coded as NA.
A data frame with 606 observations on the following 110 variables.
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
For a more detailed description of this data set, see the help file
chorizon in package mvoutlier.
Kola Project (1993-1998)
Reimann, C., Filzmoser, P., Garrett, R.G. and Dutter, R. (2008) Statistical Data Analysis Explained: Applied Environmental Statistics with R. Wiley.
data(chorizonDL, package = "VIM") summary(chorizonDL)data(chorizonDL, package = "VIM") summary(chorizonDL)
This is a modified version of the original training data set taken from the UCI repository, see reference. The modifications are only related to having appropriate levels for factor variables. This data set is about horse diseases where the task is to determine, if the lesion of the horse was surgical or not.
A training data frame with 300 observations on the following 31 variables.
yes or no
1 equals an adult horse, 2 is a horse younger than 6 months
ID
rectal temperature
heart rate in beats per minute
a normal rate is between 8 and 10
temperature of extremities
factor with four categories
a clinical judgement. The longer the refill, the poorer the circulation. Possible values are 1 = < 3 seconds and 2 = >= 3 seconds
a subjective judgement of the horse's pain level
an indication of the activity in the horse's gut. As the gut becomes more distended or the horse becomes more toxic, the activity decreases
An animal with abdominal distension is likely to be painful and have reduced gut motility. A horse with severe abdominal distension is likely to require surgery just tio relieve the pressure
This refers to any gas coming out of the tube. A large gas cap in the stomach is likely to give the horse discomfort
posible values are 1 = none, 2 = > 1 liter, 3 = < 1 liter. The greater amount of reflux, the more likelihood that there is some serious obstruction to the fluid passage from the rest of the intestine
scale is from 0 to 14 with 7 being neutral. Normal values are in the 3 to 4 range
Rectal examination. Absent feces probably indicates an obstruction
abdomen. possible values 1 = normal, 2 = other, 3 = firm feces in the large intestine, 4 = distended small intestine, 5 = distended large intestine
packed cell volume. normal range is 30 to 50. The level rises as the circulation becomes compromised or as the animal becomes dehydrated.
total protein. Normal values lie in the 6-7.5 (gms/dL) range. The higher the value the greater the dehydration
Abdominocentesis appearance. A needle is put in the horse's abdomen and fluid is obtained from the abdominal cavity
abdomcentesis total protein. The higher the level of protein the more likely it is to have a compromised gut. Values are in gms/dL
What eventually happened to the horse?
retrospectively, was the problem (lesion) surgical?
type of lesion
type of lesion
type of lesion
temperature of extremities (ordered)
mucous membranes. A subjective measurement of colour
different recodings of mucous membrances
https://archive.ics.uci.edu/ml/datasets/Horse+Colic Creators: Mary McLeish & Matt Cecile, Department of Computer Science, University of Guelph, Guelph, Ontario, Canada N1G 2W1 Donor: Will Taylor
data(colic) aggr(colic)data(colic) aggr(colic)
Subset of the collision data from December 20. to December 31. 2018 from NYCD.
Each record represents a collision in NYC by city, borough, precinct and cross street.
https://data.cityofnewyork.us/Public-Safety/NYPD-Motor-Vehicle-Collisions/h9gi-nx95
data(collisions) aggr(collisions)data(collisions) aggr(collisions)
Colored map in which the proportion or amount of missing/imputed values in each region is coded according to a continuous or discrete color scheme. The sequential color palette may thereby be computed in the HCL or the RGB color space.
colormapMiss( x, region, map, imp_index = NULL, prop = TRUE, polysRegion = 1:length(x), range = NULL, n = NULL, col = c("red", "orange"), gamma = 2.2, fixup = TRUE, coords = NULL, numbers = TRUE, digits = 2, cex.numbers = 0.8, col.numbers = par("fg"), legend = TRUE, interactive = TRUE, ... ) colormapMissLegend( xleft, ybottom, xright, ytop, cmap, n = 1000, horizontal = TRUE, digits = 2, cex.numbers = 0.8, col.numbers = par("fg"), ... )colormapMiss( x, region, map, imp_index = NULL, prop = TRUE, polysRegion = 1:length(x), range = NULL, n = NULL, col = c("red", "orange"), gamma = 2.2, fixup = TRUE, coords = NULL, numbers = TRUE, digits = 2, cex.numbers = 0.8, col.numbers = par("fg"), legend = TRUE, interactive = TRUE, ... ) colormapMissLegend( xleft, ybottom, xright, ytop, cmap, n = 1000, horizontal = TRUE, digits = 2, cex.numbers = 0.8, col.numbers = par("fg"), ... )
x |
a numeric vector. |
region |
a vector or factor of the same length as |
map |
an object of any class that contains polygons and provides its
own plot method (e.g., |
imp_index |
a logical-vector indicating which values of ‘x’ have
been imputed. If given, it is used for highlighting and the colors are
adjusted according to the given colors for imputed variables (see
|
prop |
a logical indicating whether the proportion of missing/imputed values should be used rather than the total amount. |
polysRegion |
a numeric vector specifying the region that each polygon belongs to. |
range |
a numeric vector of length two specifying the range (minimum and maximum) of the proportion or amount of missing/imputed values to be used for the color scheme. |
n |
for |
col |
the color range (start end end) to be used. RGB colors may be
specified as character strings or as objects of class
" |
gamma |
numeric; the display gamma value (see
|
fixup |
a logical indicating whether the colors should be corrected to
valid RGB values (see |
coords |
a matrix or |
numbers |
a logical indicating whether the corresponding proportions or numbers of missing/imputed values should be used as labels for the regions. |
digits |
the number of digits to be used in the labels (in case of proportions). |
cex.numbers |
the character expansion factor to be used for the labels. |
col.numbers |
the color to be used for the labels. |
legend |
a logical indicating whether a legend should be plotted. |
interactive |
a logical indicating whether more detailed information about missing/imputed values should be displayed interactively (see ‘Details’). |
... |
further arguments to be passed to |
xleft |
left x position of the legend. |
ybottom |
bottom y position of the legend. |
xright |
right x position of the legend. |
ytop |
top y position of the legend. |
cmap |
a list as returned by |
horizontal |
a logical indicating whether the legend should be drawn horizontally or vertically. |
The proportion or amount of missing/imputed values in x of each
region is coded according to a continuous or discrete color scheme in the
color range defined by col. In addition, the proportions or numbers
can be shown as labels in the regions.
If interactive is TRUE, clicking in a region displays more
detailed information about missing/imputed values on the console. Clicking
outside the borders quits the interactive session.
colormapMiss returns a list with the following components:
nmiss a numeric vector containing the number of missing/imputed values in each region.
nobs a numeric vector containing the number of observations in each region.
pmiss a numeric vector containing the proportion of missing values in each region.
prop a logical indicating whether the proportion of missing/imputed values have been used rather than the total amount.
range the range of the proportion or amount of missing/imputed values corresponding to the color range.
n either a positive integer giving the number of equally spaced
cut-off points for a discretized color scheme, or NULL for a
continuous color scheme.
start the start color of the color scheme.
end the end color of the color scheme.
space a character string giving the color space (either
"rgb" for RGB colors or "hcl" for HCL colors).
gamma numeric; the display gamma value (see
colorspace::hex()).
fixup a logical indicating whether the colors have been
corrected to valid RGB values (see colorspace::hex()).
Some of the argument names and positions have changed with versions
1.3 and 1.4 due to extended functionality and for more consistency with
other plot functions in VIM. For back compatibility, the arguments
cex.text and col.text can still be supplied to ...{}
and are handled correctly. Nevertheless, they are deprecated and no longer
documented. Use cex.numbers and col.numbers instead.
Andreas Alfons, modifications to show imputed values by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
colSequence(), growdotMiss(),
mapMiss()
Compute color sequences by linear interpolation based on a continuous color scheme between certain start and end colors. Color sequences may thereby be computed in the HCL or RGB color space.
colSequence(p, start, end, space = c("hcl", "rgb"), ...) colSequenceRGB(p, start, end, fixup = TRUE, ...) colSequenceHCL(p, start, end, fixup = TRUE, ...)colSequence(p, start, end, space = c("hcl", "rgb"), ...) colSequenceRGB(p, start, end, fixup = TRUE, ...) colSequenceHCL(p, start, end, fixup = TRUE, ...)
p |
a numeric vector with values between 0 and 1 giving values to be used for interpolation between the start and end color (0 corresponds to the start color, 1 to the end color). |
start, end
|
the start and end color, respectively. For HCL colors,
each can be supplied as a vector of length three (hue, chroma, luminance) or
an object of class " |
space |
character string; if |
... |
for |
fixup |
a logical indicating whether the colors should be corrected to
valid RGB values (see |
A character vector containing hexadecimal strings of the form
"#RRGGBB".
Andreas Alfons
Zeileis, A., Hornik, K., Murrell, P. (2009) Escaping RGBland: Selecting colors for statistical graphics. Computational Statistics & Data Analysis, 53 (9), 1259–1270.
colorspace::hex(),
colorspace::sequential_hcl()
p <- c(0, 0.3, 0.55, 0.8, 1) ## HCL colors colSequence(p, c(0, 0, 100), c(0, 100, 50)) colSequence(p, polarLUV(L=90, C=30, H=90), c(0, 100, 50)) ## RGB colors colSequence(p, c(1, 1, 1), c(1, 0, 0), space="rgb") colSequence(p, RGB(1, 1, 0), "red")p <- c(0, 0.3, 0.55, 0.8, 1) ## HCL colors colSequence(p, c(0, 0, 100), c(0, 100, 50)) colSequence(p, polarLUV(L=90, C=30, H=90), c(0, 100, 50)) ## RGB colors colSequence(p, c(1, 1, 1), c(1, 0, 0), space="rgb") colSequence(p, RGB(1, 1, 0), "red")
Count the number of infinite or missing values in a vector.
countInf(x)countInf(x)
x |
a vector. |
countInf returns the number of infinite values in x.
countNA returns the number of missing values in x.
Andreas Alfons
data(sleep, package="VIM") countInf(log(sleep$Dream)) countNA(sleep$Dream)data(sleep, package="VIM") countInf(log(sleep$Dream)) countNA(sleep$Dream)
A synthetic replacement for the Pima Indians Diabetes data: 768 observations
on 9 variables, a binary target (Outcome) and medical predictors such as
the number of pregnancies, plasma glucose, BMI, insulin level and age.
Every value is synthetic; no row corresponds to a real person.
A data frame with 768 observations on the following 9 variables.
Number of times pregnant (0 is a valid value)
Plasma glucose concentration at 2 hours in an oral glucose tolerance test
Diastolic blood pressure (mm Hg)
Triceps skin fold thickness (mm)
2-Hour serum insulin (mu U/ml)
Body mass index (weight in kg/(height in m)^2)
Diabetes pedigree function
Age in years
Diabetes (yes or no)
The original data were collected by the National Institute of Diabetes and Digestive and Kidney Diseases from female patients of Pima Indian heritage aged at least 21. The team that collected them has stated that the data should not have been distributed and has asked for redistribution to stop, while a large body of teaching material and package examples depends on them. This synthetic version exists so that such material keeps working without real patient records being circulated.
The schema follows PimaIndiansDiabetes2 from package mlbench:
physically impossible values (a zero glucose level, blood pressure, skin
fold thickness, insulin level or BMI) are coded as NA, whereas 0
pregnancies is a valid value. Column names, types and the levels of
Outcome are those VIM has used since version 6, so existing code runs
unchanged; only the values differ from the real data shipped before
VIM 7.3.0.
Missing values in the original are not scattered at random: BloodPressure,
SkinThickness and Insulin are frequently missing together, and the
pattern is age-related. The pattern itself was synthesised as a variable
and the missing values imposed from it, so that complete-case and
imputation examples behave as they did before (placing missing values
independently would produce the joint pattern about five times instead of
the observed 19 to 24).
Results computed on these data resemble published analyses of the original without matching them: a logistic regression reaches an AUC of 0.868 against 0.862 on the original, and a model fitted only on the synthetic data reaches 0.854 on the real records. Individual correlations are less reliable – most come out slightly weaker than in the original, but the association between number of pregnancies and age is considerably stronger (0.74 against 0.54). Use the data for teaching, examples and method demonstrations; any result computed on them describes the synthesis, not the Pima population, and must not be read as evidence about diabetes.
Matthias Templ [email protected] (synthetic version)
Synthetic. Generated by Matthias Templ from PimaIndiansDiabetes2
(package mlbench) with the synvey package – sequential robust
synthesis with a random-forest backend and the missingness pattern treated
as a structural variable (synvey 0.1.0, R 4.5.2, seed 20260804):
SynthDiabetes <- synvey::robsynth(PimaIndiansDiabetes2,
method = "robust_rf",
missingness = "structural",
coarsen = "age",
target = "sample",
seed = 20260804)$synth
This configuration was selected from a comparison of five synthesis
packages under two designs for the missingness mechanism. Candidates
reproducing any original record verbatim were excluded; the data set
contains no such record. synvey is not on CRAN; it is available from
https://github.com/matthias-da/synvey. For VIM the columns were renamed to
the historical names (pregnant, glucose, pressure, triceps,
insulin, mass, pedigree, age, diabetes became Pregnancies,
Glucose, BloodPressure, SkinThickness, Insulin, BMI,
DiabetesPedigreeFunction, Age, Outcome), counts are stored as
integers and the Outcome levels neg/pos as no/yes. The original
data are neither distributed with VIM nor needed to use this data set.
Smith, J.W., Everhart, J.E., Dickson, W.C., Knowler, W.C., & Johannes, R.S. (1988). Using the ADAP learning algorithm to forecast the onset of diabetes mellitus. In Proceedings of the Symposium on Computer Applications and Medical Care (pp. 261–265). IEEE Computer Society Press. https://pmc.ncbi.nlm.nih.gov/articles/PMC2245318/ (The study behind the original data; the original data are not redistributed here.)
data(diabetes) summary(diabetes) # missingness is structured rather than scattered aggr(diabetes)data(diabetes) summary(diabetes) # missingness is structured rather than scattered aggr(diabetes)
Various error measures evaluating the quality of imputations
evaluation(x, y, m, vartypes = "guess", where = NULL) nrmse(x, y, m) pfc(x, y, m) msecov(x, y) msecor(x, y)evaluation(x, y, m, vartypes = "guess", where = NULL) nrmse(x, y, m) pfc(x, y, m) msecov(x, y) msecor(x, y)
x |
matrix or data frame |
y |
matrix or data frame of the same size as x |
m |
the indicator matrix for missing cells (kept for backward
compatibility; |
vartypes |
a vector of length ncol(x) specifying the variable types
( |
where |
the indicator matrix for missing cells under its documented
name – the amputed-cell mask as returned in |
This function has been mainly written for procudures that evaluate imputation or replacement of rounded zeros. The ni parameter can thus, e.g. be used for expressing the number of rounded zeros.
the error measures value
Matthias Templ
M. Templ, A. Kowarik, P. Filzmoser (2011) Iterative stepwise regression imputation using standard and robust methods. Computational Statistics & Data Analysis, Vol. 55, pp. 2793-2806.
data(iris) iris_orig <- iris_imp <- iris iris_imp$Sepal.Length[sample(1:nrow(iris), 10)] <- NA iris_imp$Sepal.Width[sample(1:nrow(iris), 10)] <- NA iris_imp$Species[sample(1:nrow(iris), 10)] <- NA m <- is.na(iris_imp) iris_imp <- kNN(iris_imp, imp_var = FALSE) evaluation(iris_orig, iris_imp, m = m, vartypes = c(rep("numeric", 4), "factor")) msecov(iris_orig[, 1:4], iris_imp[, 1:4])data(iris) iris_orig <- iris_imp <- iris iris_imp$Sepal.Length[sample(1:nrow(iris), 10)] <- NA iris_imp$Sepal.Width[sample(1:nrow(iris), 10)] <- NA iris_imp$Species[sample(1:nrow(iris), 10)] <- NA m <- is.na(iris_imp) iris_imp <- kNN(iris_imp, imp_var = FALSE) evaluation(iris_orig, iris_imp, m = m, vartypes = c(rep("numeric", 4), "factor")) msecov(iris_orig[, 1:4], iris_imp[, 1:4])
The relative consumption of certain food items in European and Scandinavian countries.
A data frame with 16 observations on the following 21 variables.
The numbers represent the percentage of the population consuming that food type.
https://openmv.net/info/food-consumption
data(food) str(food) aggr(food)data(food) str(food) aggr(food)
Computes the average missing value gap of a vector.
gapMiss(x, what = mean)gapMiss(x, what = mean)
x |
a numeric vector |
what |
default is the arithmetic mean. One can include an own function that returns a vector of lenght 1 (e.g. median) |
The length of each sequence of missing values (gap) in a vector is calculated and the mean gap is reported
The gap statistics
Matthias Templ based on a suggestion and draft from Huang Tian Yuan.
v <- rnorm(20) v[3] <- NA v[6:9] <- NA v[13:17] <- NA v gapMiss(v) gapMiss(v, what = median) gapMiss(v, what = function(x) mean(x, trim = 0.1)) gapMiss(v, what = var)v <- rnorm(20) v[3] <- NA v[6:9] <- NA v[13:17] <- NA v gapMiss(v) gapMiss(v, what = median) gapMiss(v, what = function(x) mean(x, trim = 0.1)) gapMiss(v, what = var)
The function gowerD is used by kNN to compute the distances for numerical, factor ordered and semi-continous variables.
gowerD( data.x, data.y = data.x, weights = rep(1, ncol(data.x)), numerical = colnames(data.x), factors = vector(), orders = vector(), mixed = vector(), levOrders = vector(), mixed.constant = rep(0, length(mixed)), returnIndex = FALSE, nMin = 1L, returnMin = FALSE, methodStand = "range" )gowerD( data.x, data.y = data.x, weights = rep(1, ncol(data.x)), numerical = colnames(data.x), factors = vector(), orders = vector(), mixed = vector(), levOrders = vector(), mixed.constant = rep(0, length(mixed)), returnIndex = FALSE, nMin = 1L, returnMin = FALSE, methodStand = "range" )
data.x |
data frame |
data.y |
data frame |
weights |
numeric vector providing weights for the observations in x |
numerical |
names of numerical variables |
factors |
names of factor variables |
orders |
names of ordered variables |
mixed |
names of mixed variables |
levOrders |
vector with number of levels for each orders variable |
mixed.constant |
vector with length equal to the number of semi-continuous variables specifying the point of the semi-continuous distribution with non-zero probability |
returnIndex |
logical if TRUE return the index of the minimum distance |
nMin |
integer number of values with smallest distance to be returned |
returnMin |
logical if the computed distances for the indices should be returned |
methodStand |
character either "range" or "iqr", iqr is more robust for outliers |
Numerical and semi-continuous (mixed) variables are standardised by
their range (or IQR, see methodStand) before the distance is computed; for
mixed variables the point mass (mixed.constant) is excluded from the range
estimate and scaled along with the data.
Missing values in a distance variable are replaced by a sentinel (the pooled column maximum plus one) after standardisation. Two records both missing the same variable therefore have distance 0 on it, and a missing-vs-observed pair contributes up to about 2 (rather than a variable's nominal maximum of 1). This sentinel convention departs from Gower's (1971) omit-and-renormalise rule and biases nearest-neighbour selection towards records that share the same missingness pattern.
The distance computation is parallelised with OpenMP where R was built with
OpenMP support. The number of threads is getOption("VIM.ncores"); if the
option is unset, at most 2 threads are used while the package is checked
(R CMD check sets _R_CHECK_LIMIT_CORES_; CRAN policy allows at most two
cores) and OpenMP's default – typically all cores, or OMP_NUM_THREADS –
otherwise. Results do not depend on the number of threads.
returnIndex=FALSE: a numerical matrix n x m with the computed distances returnIndex=TRUE: a named list with "ind" containing the requested indices and "mins" the computed distances
data(sleep) # all variables used as numerical gowerD(sleep) # split in numerical an gowerD(sleep, numerical = c("BodyWgt", "BrainWgt", "NonD", "Dream", "Sleep", "Span", "Gest"), orders = c("Pred","Exp","Danger"), levOrders = c(5,5,5)) # as before but only returning the index of the closest observation gowerD(sleep, numerical = c("BodyWgt", "BrainWgt", "NonD", "Dream", "Sleep", "Span", "Gest"), orders = c("Pred","Exp","Danger"), levOrders = c(5,5,5), returnIndex = TRUE)data(sleep) # all variables used as numerical gowerD(sleep) # split in numerical an gowerD(sleep, numerical = c("BodyWgt", "BrainWgt", "NonD", "Dream", "Sleep", "Span", "Gest"), orders = c("Pred","Exp","Danger"), levOrders = c(5,5,5)) # as before but only returning the index of the closest observation gowerD(sleep, numerical = c("BodyWgt", "BrainWgt", "NonD", "Dream", "Sleep", "Span", "Gest"), orders = c("Pred","Exp","Danger"), levOrders = c(5,5,5), returnIndex = TRUE)
Map with dots whose sizes correspond to the values in a certain variable. Observations with missing/imputed values in additional variables are highlighted.
growdotMiss( x, coords, map, pos = 1, delimiter = NULL, selection = c("any", "all"), log = FALSE, col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), border = par("bg"), alpha = NULL, scale = NULL, size = NULL, exp = c(0, 0.95, 0.05), col.map = grey(0.5), legend = TRUE, legtitle = "Legend", cex.legtitle = par("cex"), cex.legtext = par("cex"), ncircles = 6, ndigits = 1, interactive = TRUE, ... )growdotMiss( x, coords, map, pos = 1, delimiter = NULL, selection = c("any", "all"), log = FALSE, col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), border = par("bg"), alpha = NULL, scale = NULL, size = NULL, exp = c(0, 0.95, 0.05), col.map = grey(0.5), legend = TRUE, legtitle = "Legend", cex.legtitle = par("cex"), cex.legtext = par("cex"), ncircles = 6, ndigits = 1, interactive = TRUE, ... )
x |
a vector, matrix or |
coords |
a matrix or |
map |
a background map to be passed to |
pos |
a numeric value giving the index of the variable determining the dot sizes. |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
selection |
the selection method for highlighting missing/imputed
values in multiple additional variables. Possible values are |
log |
a logical indicating whether the variable given by |
col |
a vector of length six giving the colors to be used in the plot. If only one color is supplied, it is used for the borders of non-highlighted dots and the surface area of highlighted dots. Else if two colors are supplied, they are recycled. |
border |
a vector of length four giving the colors to be used for the
borders of the growing dots. Use |
alpha |
a numeric value between 0 and 1 giving the level of
transparency of the colors, or |
scale |
scaling factor of the map. |
size |
a vector of length two giving the sizes for the smallest and largest dots. |
exp |
a vector of length three giving the factors that define the shape of the exponential function (see ‘Details’). |
col.map |
the color to be used for the background map. |
legend |
a logical indicating whether a legend should be plotted. |
legtitle |
the title for the legend. |
cex.legtitle |
the character expansion factor to be used for the title of the legend. |
cex.legtext |
the character expansion factor to be used in the legend. |
ncircles |
the number of circles displayed in the legend. |
ndigits |
the number of digits displayed in the legend. Note that \
this is just a suggestion (see |
interactive |
a logical indicating whether information about certain observations can be displayed interactively (see ‘Details’). |
... |
for |
The smallest dots correspond to the 10\ the 99\ defining the shape of the exponential function. Missings/imputed missings in the variable of interest will be drawn as rectangles.
If interactive=TRUE, detailed information for an observation can be
printed on the console by clicking on the corresponding point. Clicking in
a region that does not contain any points quits the interactive session.
The function was renamed to growdotMiss in version 1.3.
bubbleMiss is a (deprecated) wrapper for growdotMiss for back
compatibility with older versions. However, due to extended functionality,
some of the argument positions have changed.
The code is based on (removed from CRAN) bubbleFIN from package StatDA.
Andreas Alfons, Matthias Templ, Peter Filzmoser, Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
bgmap(), mapMiss(),
colormapMiss()
data(chorizonDL, package = "VIM") data(kola.background, package = "VIM") coo <- chorizonDL[, c("XCOO", "YCOO")] ## for missing values x <- chorizonDL[, c("Ca","As", "Bi")] growdotMiss(x, coo, kola.background, border = "white") ## for imputed values x_imp <- kNN(chorizonDL[,c("Ca","As","Bi" )]) growdotMiss(x_imp, coo, kola.background, delimiter = "_imp", border = "white")data(chorizonDL, package = "VIM") data(kola.background, package = "VIM") coo <- chorizonDL[, c("XCOO", "YCOO")] ## for missing values x <- chorizonDL[, c("Ca","As", "Bi")] growdotMiss(x, coo, kola.background, border = "white") ## for imputed values x_imp <- kNN(chorizonDL[,c("Ca","As","Bi" )]) growdotMiss(x_imp, coo, kola.background, delimiter = "_imp", border = "white")
Histogram with highlighting of missing/imputed values in other variables by splitting each bin into two parts. Additionally, information about missing/imputed values in the variable of interest is shown on the right hand side.
histMiss( x, delimiter = NULL, pos = 1, selection = c("any", "all"), breaks = "Sturges", right = TRUE, col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), border = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, only.miss = TRUE, miss.labels = axes, interactive = TRUE, ... )histMiss( x, delimiter = NULL, pos = 1, selection = c("any", "all"), breaks = "Sturges", right = TRUE, col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), border = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, only.miss = TRUE, miss.labels = axes, interactive = TRUE, ... )
x |
a vector, matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
pos |
a numeric value giving the index of the variable of interest.
Additional variables in |
selection |
the selection method for highlighting missing/imputed
values in multiple additional variables. Possible values are |
breaks |
either a character string naming an algorithm to compute the
breakpoints (see |
right |
logical; if |
col |
a vector of length six giving the colors to be used. If only one color is supplied, the bars are transparent and the supplied color is used for highlighting missing/imputed values. Else if two colors are supplied, they are recycled. |
border |
the color to be used for the border of the cells. Use
|
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
axes |
a logical indicating whether axes should be drawn on the plot. |
only.miss |
logical; if |
miss.labels |
either a logical indicating whether label(s) should be plotted below the bar(s) on the right hand side, or a character string or vector giving the label(s) (see ‘Details’). |
interactive |
a logical indicating whether the variables can be switched interactively (see ‘Details’). |
... |
further graphical parameters to be passed to
|
If more than one variable is supplied, the bins for the variable of interest will be split according to missingness/number of imputed missings in the additional variables.
If only.miss=TRUE, the missing/imputed values in the variable of
interest are visualized by one bar on the right hand side. If additional
variables are supplied, this bar is again split into two parts according to
missingness/number of imputed missings in the additional variables.
Otherwise, a small barplot consisting of two bars is drawn on the right hand
side. The first bar corresponds to observed values in the variable of
interest and the second bar to missing/imputed values. Since these two bars
are not on the same scale as the main barplot, a second y-axis is plotted on
the right (if axes=TRUE). Each of the two bars are again split into
two parts according to missingness/number of imputed missings in the
additional variables. Note that this display does not make sense if only
one variable is supplied, therefore only.miss is ignored in that
case.
If interactive=TRUE, clicking in the left margin of the plot results
in switching to the previous variable and clicking in the right margin
results in switching to the next variable. Clicking anywhere else on the
graphics device quits the interactive session. When switching to a
categorical variable, a barplot is produced rather than a histogram.
a list with the following components:
breaks the breakpoints.
counts the number of observations in each cell.
missings the number of highlighted observations in each cell.
mids the cell midpoints.
Some of the argument names and positions have changed with version 1.3
due to extended functionality and for more consistency with other plot
functions in VIM. For back compatibility, the arguments
axisnames and names.miss can still be supplied to
...{} and are handled correctly. Nevertheless, they are deprecated
and no longer documented. Use miss.labels instead.
Andreas Alfons, Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(tao, package = "VIM") ## for missing values x <- tao[, c("Air.Temp", "Humidity")] histMiss(x) histMiss(x, only.miss = FALSE) ## for imputed values x_IMPUTED <- kNN(tao[, c("Air.Temp", "Humidity")]) histMiss(x_IMPUTED, delimiter = "_imp") histMiss(x_IMPUTED, delimiter = "_imp", only.miss = FALSE)data(tao, package = "VIM") ## for missing values x <- tao[, c("Air.Temp", "Humidity")] histMiss(x) histMiss(x, only.miss = FALSE) ## for imputed values x_IMPUTED <- kNN(tao[, c("Air.Temp", "Humidity")]) histMiss(x_IMPUTED, delimiter = "_imp") histMiss(x_IMPUTED, delimiter = "_imp", only.miss = FALSE)
Implementation of the popular Sequential, Random (within a domain) hot-deck algorithm for imputation.
hotdeck( data, variable = NULL, ord_var = NULL, domain_var = NULL, makeNA = NULL, NAcond = NULL, impNA = TRUE, donorcond = NULL, imp_var = TRUE, imp_suffix = "imp" )hotdeck( data, variable = NULL, ord_var = NULL, domain_var = NULL, makeNA = NULL, NAcond = NULL, impNA = TRUE, donorcond = NULL, imp_var = TRUE, imp_suffix = "imp" )
data |
data.frame or matrix |
variable |
variables where missing values should be imputed (not overlapping with ord_var) |
ord_var |
variables for sorting the data set before imputation (not overlapping with variable) |
domain_var |
variables for building domains and impute within these domains |
makeNA |
list of length equal to the number of variables, with values, that should be converted to NA for each variable |
NAcond |
list of length equal to the number of variables, with a condition for imputing a NA |
impNA |
TRUE/FALSE whether NA should be imputed |
donorcond |
list of length equal to the number of variables, with a donorcond condition as character string. e.g. ">5" or c(">5","<10). If the list element for a variable is NULL no condition will be applied for this variable. |
imp_var |
TRUE/FALSE if a TRUE/FALSE variables for each imputed variable should be created show the imputation status |
imp_suffix |
suffix for the TRUE/FALSE variables showing the imputation status |
the imputed data set.
If the sequential hotdeck does not lead to a suitable, a random donor in the group will be used.
Alexander Kowarik
A. Kowarik, M. Templ (2016) Imputation with R package VIM. Journal of Statistical Software, 74(7), 1-16.
Other imputation methods:
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep) sleepI <- hotdeck(sleep) sleepI2 <- hotdeck(sleep,ord_var="BodyWgt",domain_var="Pred") # Usage of donorcond in a simple example sleepI3 <- hotdeck( sleep, variable = c("NonD", "Dream", "Sleep", "Span", "Gest"), ord_var = "BodyWgt", domain_var = "Pred", donorcond = list(">4", "<17", ">1.5", "%between%c(8,13)", ">5") ) set.seed(132) nRows <- 1e3 # Generate a data set with nRows rows and several variables x <- data.frame( x = rnorm(nRows), y = rnorm(nRows), z = sample(LETTERS, nRows, replace = TRUE), d1 = sample(LETTERS[1:3], nRows, replace = TRUE), d2 = sample(LETTERS[1:2], nRows, replace = TRUE), o1 = rnorm(nRows), o2 = rnorm(nRows), o3 = rnorm(100) ) origX <- x x[sample(1:nRows,nRows/10), 1] <- NA x[sample(1:nRows,nRows/10), 2] <- NA x[sample(1:nRows,nRows/10), 3] <- NA x[sample(1:nRows,nRows/10), 4] <- NA xImp <- hotdeck(x,ord_var = c("o1", "o2", "o3"), domain_var = "d2")data(sleep) sleepI <- hotdeck(sleep) sleepI2 <- hotdeck(sleep,ord_var="BodyWgt",domain_var="Pred") # Usage of donorcond in a simple example sleepI3 <- hotdeck( sleep, variable = c("NonD", "Dream", "Sleep", "Span", "Gest"), ord_var = "BodyWgt", domain_var = "Pred", donorcond = list(">4", "<17", ">1.5", "%between%c(8,13)", ">5") ) set.seed(132) nRows <- 1e3 # Generate a data set with nRows rows and several variables x <- data.frame( x = rnorm(nRows), y = rnorm(nRows), z = sample(LETTERS, nRows, replace = TRUE), d1 = sample(LETTERS[1:3], nRows, replace = TRUE), d2 = sample(LETTERS[1:2], nRows, replace = TRUE), o1 = rnorm(nRows), o2 = rnorm(nRows), o3 = rnorm(100) ) origX <- x x[sample(1:nRows,nRows/10), 1] <- NA x[sample(1:nRows,nRows/10), 2] <- NA x[sample(1:nRows,nRows/10), 3] <- NA x[sample(1:nRows,nRows/10), 4] <- NA xImp <- hotdeck(x,ord_var = c("o1", "o2", "o3"), domain_var = "d2")
Greedy algorithm for EM-PCA including robust methods
impPCA( x, method = "classical", m = 1, eps = 0.5, k = ncol(x) - 1, maxit = 100, boot = FALSE, verbose = TRUE )impPCA( x, method = "classical", m = 1, eps = 0.5, k = ncol(x) - 1, maxit = 100, boot = FALSE, verbose = TRUE )
x |
data.frame or matrix |
method |
|
m |
number of multiple imputations (only if parameter |
eps |
threshold for convergence |
k |
number of principal components for reconstruction of |
maxit |
maximum number of iterations |
boot |
residual bootstrap (if |
verbose |
TRUE/FALSE if additional information about the imputation process should be printed |
the imputed data set. If boot = FALSE this is a data.frame.
If boot = TRUE this is a list where each list element contains a data.frame.
Matthias Templ
Serneels, Sven and Verdonck, Tim (2008). Principal component analysis for data containing outliers and missing elements. Computational Statistics and Data Analysis, Elsevier, vol. 52(3), pages 1712-1727
Other imputation methods:
hotdeck(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(Animals, package = "MASS") Animals$brain[19] <- Animals$brain[19] + 0.01 Animals <- log(Animals) colnames(Animals) <- c("log(body)", "log(brain)") Animals_na <- Animals probs <- abs(Animals$`log(body)`^2) probs <- rep(0.5, nrow(Animals)) probs[c(6,16,26)] <- 0 set.seed(1234) Animals_na[sample(1:nrow(Animals), 10, prob = probs), "log(brain)"] <- NA w <- is.na(Animals_na$`log(brain)`) impPCA(Animals_na) impPCA(Animals_na, method = "mcd") impPCA(Animals_na, boot = TRUE, m = 10) impPCA(Animals_na, method = "mcd", boot = TRUE)[[1]] plot(`log(brain)` ~ `log(body)`, data = Animals, type = "n", ylab = "", xlab="") mtext(text = "impPCA robust", side = 3) points(Animals$`log(body)`[!w], Animals$`log(brain)`[!w]) points(Animals$`log(body)`[w], Animals$`log(brain)`[w], col = "grey", pch = 17) imputed <- impPCA(Animals_na, method = "mcd", boot = TRUE)[[1]] colnames(imputed) <- c("log(body)", "log(brain)") points(imputed$`log(body)`[w], imputed$`log(brain)`[w], col = "red", pch = 20, cex = 1.4) segments(x0 = Animals$`log(body)`[w], x1 = imputed$`log(body)`[w], y0 = Animals$`log(brain)`[w], y1 = imputed$`log(brain)`[w], lty = 2, col = "grey") legend("topleft", legend = c("non-missings", "set to missing", "imputed values"), pch = c(1,17,20), col = c("black","grey","red"), cex = 0.7) mape <- round(100* 1/sum(is.na(Animals_na$`log(brain)`)) * sum(abs((Animals$`log(brain)` - imputed$`log(brain)`) / Animals$`log(brain)`)), 2) s2 <- var(Animals$`log(brain)`) nrmse <- round(sqrt(1/sum(is.na(Animals_na$`log(brain)`)) * sum(abs((Animals$`log(brain)` - imputed$`log(brain)`) / s2))), 2) text(x = 8, y = 1.5, labels = paste("MAPE =", mape)) text(x = 8, y = 0.5, labels = paste("NRMSE =", nrmse))data(Animals, package = "MASS") Animals$brain[19] <- Animals$brain[19] + 0.01 Animals <- log(Animals) colnames(Animals) <- c("log(body)", "log(brain)") Animals_na <- Animals probs <- abs(Animals$`log(body)`^2) probs <- rep(0.5, nrow(Animals)) probs[c(6,16,26)] <- 0 set.seed(1234) Animals_na[sample(1:nrow(Animals), 10, prob = probs), "log(brain)"] <- NA w <- is.na(Animals_na$`log(brain)`) impPCA(Animals_na) impPCA(Animals_na, method = "mcd") impPCA(Animals_na, boot = TRUE, m = 10) impPCA(Animals_na, method = "mcd", boot = TRUE)[[1]] plot(`log(brain)` ~ `log(body)`, data = Animals, type = "n", ylab = "", xlab="") mtext(text = "impPCA robust", side = 3) points(Animals$`log(body)`[!w], Animals$`log(brain)`[!w]) points(Animals$`log(body)`[w], Animals$`log(brain)`[w], col = "grey", pch = 17) imputed <- impPCA(Animals_na, method = "mcd", boot = TRUE)[[1]] colnames(imputed) <- c("log(body)", "log(brain)") points(imputed$`log(body)`[w], imputed$`log(brain)`[w], col = "red", pch = 20, cex = 1.4) segments(x0 = Animals$`log(body)`[w], x1 = imputed$`log(body)`[w], y0 = Animals$`log(brain)`[w], y1 = imputed$`log(brain)`[w], lty = 2, col = "grey") legend("topleft", legend = c("non-missings", "set to missing", "imputed values"), pch = c(1,17,20), col = c("black","grey","red"), cex = 0.7) mape <- round(100* 1/sum(is.na(Animals_na$`log(brain)`)) * sum(abs((Animals$`log(brain)` - imputed$`log(brain)`) / Animals$`log(brain)`)), 2) s2 <- var(Animals$`log(brain)`) nrmse <- round(sqrt(1/sum(is.na(Animals_na$`log(brain)`)) * sum(abs((Animals$`log(brain)` - imputed$`log(brain)`) / s2))), 2) text(x = 8, y = 1.5, labels = paste("MAPE =", mape)) text(x = 8, y = 0.5, labels = paste("NRMSE =", nrmse))
EM algorithm with latent contamination indicators that jointly estimates clean distribution parameters and identifies cellwise outliers. Each continuous cell has a posterior probability of being clean vs contaminated. The clean distribution is modeled as multivariate normal for continuous variables, with categorical variables handled via conditional multinomial logistic regression.
imputeCellEM( data, maxit_em = 100, eps_em = 0.005, gamma_init = 3, eps_init = 0.1, uncert = "conditional", conditioning = "weighted", trust_min = 0.5, trace = FALSE )imputeCellEM( data, maxit_em = 100, eps_em = 0.005, gamma_init = 3, eps_init = 0.1, uncert = "conditional", conditioning = "weighted", trust_min = 0.5, trace = FALSE )
data |
data.frame with missing values (mixed continuous + categorical). |
maxit_em |
maximum EM iterations (default: 100). |
eps_em |
convergence tolerance on the relative change in estimated parameters (mu, Sigma). Default: 5e-3. |
gamma_init |
initial scale inflation factor for the contamination
distribution. Contaminated cells are modeled as having variance
|
eps_init |
initial contamination probability per variable
(default: 0.1). Must be in |
uncert |
imputation uncertainty method: |
conditioning |
how observed cells enter the E-step conditional
moments. |
trust_min |
trust threshold in |
trace |
logical; if |
The algorithm proceeds as follows:
Initialization. Missing values are filled by
initialise (medians for continuous, modes for
categorical). Initial location and scale are estimated robustly
(median and MAD). Cell weights are initialized to 1.
E-step (for each continuous variable ,
each observation ):
Compute the conditional mean and variance of
given the other continuous variables, using the current
and .
For observed cells: compute the posterior probability
that the cell is clean vs contaminated, yielding cell
weight .
For missing cells: impute from the conditional distribution (with optional PMM).
M-step:
Update : cell-weighted mean.
Update : pairwise cell-weighted covariance
using (not row-level min).
Update contamination rates:
over
observed cells.
Update contamination scale from
weighted variance of contaminated cells.
For categorical variables: fit weighted multinomial logistic with row weights derived from continuous cell weights.
Convergence. Check relative change in
estimated parameters (, ); stop when
below eps_em or after maxit_em iterations.
The observed-data log-likelihood (sum of per-variable
conditional mixture log-likelihoods) is tracked for
diagnostics.
This method differs from cellGMM (Zaccaria et al., 2025) in using a single clean component rather than a mixture of clean clusters, and in supporting mixed continuous + categorical data.
The pseudo_loglik component is a composite (pseudo)
log-likelihood: the sum of per-variable conditional mixture
log-likelihoods, not the proper observed-data joint log-likelihood.
It is useful for monitoring convergence but should not be compared
across models or used for model selection criteria such as AIC/BIC.
This implementation is an ECM (Expectation Conditional Maximization) variant rather than a pure EM algorithm, because the conditional variance in the E-step is computed using the updated Sigma from the current M-step rather than the Sigma from the previous iteration. As a result, strict log-likelihood monotonicity is not guaranteed, but is observed empirically in practice.
A list with components:
data_imputed |
the imputed data.frame |
cellweights |
n x p matrix of posterior clean probabilities.
Continuous observed cells have values in |
mu |
estimated clean location vector (continuous variables only) |
Sigma |
estimated clean covariance matrix (continuous variables only) |
epsilon |
named numeric vector of estimated per-variable contamination rates (continuous variables only) |
converged |
logical indicating convergence |
iterations |
number of EM iterations performed |
pseudo_loglik |
numeric vector of composite (pseudo) log-likelihood values, one per iteration (computed after each M-step). This is a sum of per-variable conditional mixture log-likelihoods, not the proper observed-data joint log-likelihood. |
Model uncertainty via bootstrap (Rubin's combining rules for multiple imputation) is not yet implemented. The current version provides single imputation with stochastic uncertainty (PMM or residual draw). For valid multiple imputation, call the function repeatedly with different seeds and combine using Rubin's rules.
Matthias Templ
A.P. Dempster, N.M. Laird, D.B. Rubin (1977) Maximum Likelihood from Incomplete Data via the EM Algorithm. Journal of the Royal Statistical Society: Series B, 39(1), 1–38.
C.F.J. Wu (1983) On the Convergence Properties of the EM Algorithm. The Annals of Statistics, 11(1), 95–103.
J. Raymaekers, P.J. Rousseeuw (2024) The cellwise minimum covariance determinant estimator. Journal of the American Statistical Association, 119(548), 2610–2621.
G. Zaccaria, L.A. Garcia-Escudero, F. Greselin, A. Mayo-Iscar (2025) Cellwise outlier detection in heterogeneous populations. Technometrics, 67(4), 643–654.
M. Templ, A. Kowarik, P. Filzmoser (2011) Iterative stepwise regression imputation using standard and robust methods. Computational Statistics & Data Analysis, Vol. 55, pp. 2793–2806.
imputeCellIRMI, imputeCellM,
initialise, irmi
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep, package = "VIM") result <- imputeCellEM(sleep) head(result$data_imputed) # Inspect estimated contamination rates result$epsilon # Cell weight matrix (1 = clean, low = likely contaminated) image(result$cellweights, main = "Cell weights") # Log-likelihood trace plot(result$pseudo_loglik, type = "b", xlab = "Iteration", ylab = "Pseudo log-likelihood") # With predictive mean matching for imputation result2 <- imputeCellEM(sleep, uncert = "pmm", trace = TRUE) # Mixed data example data(testdata) result3 <- imputeCellEM(testdata$wna)data(sleep, package = "VIM") result <- imputeCellEM(sleep) head(result$data_imputed) # Inspect estimated contamination rates result$epsilon # Cell weight matrix (1 = clean, low = likely contaminated) image(result$cellweights, main = "Cell weights") # Log-likelihood trace plot(result$pseudo_loglik, type = "b", xlab = "Iteration", ylab = "Pseudo log-likelihood") # With predictive mean matching for imputation result2 <- imputeCellEM(sleep, uncert = "pmm", trace = TRUE) # Mixed data example data(testdata) result3 <- imputeCellEM(testdata$wna)
Estimates the mean structure , scatter and cell weights
of the model , where
is a design row built from the categorical variables. Detection uses the
conditional residual of a cell given the other continuous cells in its row
and the row's categorical pattern.
imputeCellGLoc( data, design = ~., weights = c("soft", "binary"), maxit = 200, eps = 0.005, alpha = 0.75, psi_c = 4.685, peer_w_min = 0.5, peer_band = .gloc_peer_band, damp = NULL, cw_crit = 1e-08, trace = FALSE, start = c("robust", "classical"), categorical = c("em", "level") )imputeCellGLoc( data, design = ~., weights = c("soft", "binary"), maxit = 200, eps = 0.005, alpha = 0.75, psi_c = 4.685, peer_w_min = 0.5, peer_band = .gloc_peer_band, damp = NULL, cw_crit = 1e-08, trace = FALSE, start = c("robust", "classical"), categorical = c("em", "level") )
data |
a |
design |
one-sided formula for the categorical mean structure.
|
weights |
|
maxit |
maximum number of outer iterations. |
eps |
convergence tolerance, applied to the scaled change in the
fitted means, to the relative change in the scatter, and to the cell
weights' fixed-point residual |
alpha |
minimum fraction of unflagged cells per column (binary corner).
The robust start of the soft corner runs cellMCD at its own tolerance,
|
psi_c |
tuning constant of the Tukey bisquare (soft corner).
|
peer_w_min |
a cell is conditioned on only when its weight exceeds
this, so that a downweighted peer is treated as absent rather than as
evidence. The threshold is applied over a narrow band rather than at a
point – a peer whose weight is within |
peer_band |
half-width of the band around Setting it changes the estimator and not only the iteration. Measured over
520 paired fits against |
damp |
relaxation factor for the soft corner's weight update.
|
cw_crit |
convergence tolerance of the EM inside
|
trace |
print progress. |
start |
starting values for the soft corner.
With |
categorical |
how missing categorical cells are treated. Two starts. Under The second start's fixed point is returned only if that run converged and
the first did not, or both converged and the second has the smaller
binary-corner objective: minus twice the Gaussian log-likelihood of the
retained residual cells
With |
With design = ~ 1 the estimator reduces to the published continuous-only
estimators: to the cellwise MCD of Raymaekers and Rousseeuw (2024) with
weights = "binary", and to the cellwise weighted maximum likelihood
estimator of Rousseeuw (2026) with weights = "soft".
The soft corner corrects the weighted scatter for its downweighting.
Without a correction the bisquare downweighting deflates the scatter by
about 21% at the default tuning, which would inflate the standardised
residuals and make the estimator over-flag. The correction is per column
and depends on , not a single constant: the weights act on
conditional residuals, so they shrink only the unpredictable part of
each cell, and they leave its covariances with the other cells unbiased to
first order. Since 7.5.1 the correction therefore adds the missing part of
each conditional variance to the diagonal and keeps the off-diagonals; see
.gloc_correct_scatter. It vanishes at psi_c = Inf. It is a
first-order correction: on clean data with five variables at correlation
0.7 (n = 10000) it returns conditional variances 4.5% too large and a block
correlation of 0.682, where the symmetric rescaling used until 7.5.0 returned
conditional variances 13% too small and a block correlation of 0.742.
The estimator is the triple and iteration stops only
when all three have settled:
,
and
. The first term is a change in the
fitted values measured in units of the scatter, not a change in a
coefficient measured against a location, so the criterion is invariant to
shifting the data; the second is relative, so it is invariant to rescaling
it; the third is the weight map's fixed-point residual, relaxation divided
out. converged = TRUE therefore means that nothing this function
returns is still moving, which is the only reading of convergence a
detection method can defend: is not a nuisance quantity here, it is
the flag set the caller uses.
The scatter condition is a formal guard rather than an active one. Across
every fit measured so far it has never been the binding constraint: at the
iteration where the other two conditions are first met it stands at most a
seventh of its own tolerance. It is there because is returned
and was the one returned quantity the rule did not test, and because it
costs nothing; it is not there because it was observed to catch anything.
The soft corner's weight update is relaxed (see .gloc_damp) to keep
the fixed-point iteration inside its contraction radius, and the factor is
adapted rather than fixed; see damp. Relaxation alone does not make
the criterion attainable: conditioning on a peer only when its weight
exceeds a threshold makes the weight map discontinuous, and a discontinuous
self-map of need not have a fixed point at all, so
before 7.4.0 the iteration could be asked to reach a state that did not
exist – and in the design = ~ . arm it usually was. The peer band
(see .gloc_peer_band) removes that, and the two work together rather
than one of them doing the work: over 260 fits of the
categorical-mean-structure arm, converged is 131 under the 7.3.1
schedule and hard cut, 181 with the relaxation floor at 0.5 and the scatter
condition but the cut still hard, and 245 with the band as well. About 40%
of the gain is the floor, the rest the band.
Convergence is not universal and should not be assumed. On that 260-fit grid it is 245, or 94%, with the failures concentrated at correlations of 0.6 and above combined with 20% of cells contaminated.
All convergence figures in this section were measured before 7.4.1, with
the classical cold start (start = "classical"); the robust start has
not been measured on that grid.
When the design does not use a factor's own contrasts attribute – the
factor has an unused level, or, under categorical = "level", its missing
values become a level of their own – the fit says so once for that factor
(since 7.5.1; see .gloc_contrast_lost), and base R's own "contrasts
dropped" warning is muffled at every design site here; the fitted means,
, and the imputations are the same under any full-rank
coding, so only B's rows change.
Continuous columns that are integer in data stay
integer in $imputed; their conditional expectations are
rounded.
A missing continuous cell is imputed by its conditional expectation given
the unflagged cells in its row, selected by the same peer rule detection
uses (peer_w_min with the peer band), in both weight corners. Until
7.4.0 the imputation conditioned on every observed cell, flagged ones
included, so a grossly contaminated cell was carried into the imputation of
its row-mates; B, Sigma and W were not affected. See
.gloc_impute.
Per-level detection (since 7.5.1). Under categorical = "em"
in the soft corner, a row with a missing categorical cell is judged once per
candidate level, or per level combination when several cells are missing. Each
candidate carries its own cell weights: its cells are compared with its own
fitted mean and conditioned on the cells that are clean under it. The E-step
scores a level by the cellwise-penalised likelihood of the binary corner, the
Gaussian log-density of the cells retained under the level minus
for each cell flagged under it, with
,
from the current scatter, and the peer band
in between (see .gloc_cat_score). B and Sigma are updated
with each candidate's weights times its posterior probability, and W
reports the posterior mixture of the candidates' weights, which
cat_weights returns. Why: until 7.5.0 detection in such a row ran at its
expected design row, where a cell that decides the level looks outlying
whenever the true level is far from the prior mean. That cell was flagged, the
E-step dropped it, and the posterior could not move, a self-locking fixed
point. On the datasets of the categorical arms of the 7.5.0 simulation at
eps = 0 (n = 200, six continuous and six categorical variables, 10
replicates per pattern), the decisive cell was flagged in 17.6-19.8% of the
rows missing the factor, and the imputed level was right in 0.809-0.861 of those
rows, against 0.965-0.986 for a classifier that uses the fit's own and
, the true prior probabilities and every observed continuous cell. A
contaminated cell is flagged under every level and pays the same penalty under
each, so it still does not steer the level. The binary corner keeps one weight
row per observation, since cellWise::cellMCD returns one: its detection
stays at the expected design row, and the lock can occur there. The soft corner
is the default. The missing continuous cells of such a row are imputed by the
posterior mixture of its candidates' conditional expectations, each taken at
that candidate's design row and conditioned on the cells that are clean under
it (.gloc_impute_mix); see imputed under Value. (Corrected: until
7.5.0 they were imputed once, at the expected design row with the row's weights,
which was the exact mixture expectation only while every level shared one
weight row.)
a list with B, Sigma, W, U,
imputed, converged, iterations, criterion,
cat_posterior, cat_prob_observed, cat_multi_missing,
cat_priors, em_starts and cat_weights.
W is the matrix of cell weights of the continuous
variables, 0 on missing cells. Under per-level detection ("em", soft
corner, a missing categorical cell; see Details) a row with a missing
categorical cell reports the posterior mixture
of its candidates' weights under the final E-step;
a row without one, and a row above the combination cap, reports its own.
imputed is data with its missing cells filled: a continuous
cell by its conditional expectation given the unflagged cells of its row, a
categorical cell (under "em") by its posterior mode. Under per-level
detection a missing continuous cell of a row that also misses a
categorical cell is imputed instead by the posterior mixture
over that
row's candidates: each candidate contributes the conditional expectation at
its own design row, conditioned on the cells that are clean under it, and the
candidates are mixed by their posterior probabilities . That is the
exact posterior mean of the cell. Every other row, a row above the
combination cap included, is imputed at its expected design row with the
returned W, as in 7.5.0.
cat_weights is NULL unless per-level detection ran. Then it is a
list with one entry per candidate of the rows below the combination cap that
miss a categorical cell, in the order of the candidate table: row, the
data row (integer); levels, a data frame of the candidate's values of
every categorical variable, observed values included – its columns are the
candidate table's factors, on the level sets the fit observed, so a
character or logical column of data comes back as a
factor; prob, the
candidate's posterior probability, the product of the marginal posteriors when
several cells are missing; and W, the candidates' cell weights, a
matrix with one row per candidate and one column per continuous variable.
W[i, ] of the fit equals colSums(prob * W) over row i's
entries.
Under categorical = "em", U holds each row's expected design
row, so U %*% B are the fitted means. cat_posterior is a
list with one matrix per categorical variable that has a missing cell: its
rows are those cells' rows (row names are row indices), its columns the
levels, its entries posterior probabilities. imputed holds the
posterior mode (ties: the first level). For multiple imputation, draw the
level from these probabilities first and the continuous cells given it.
cat_prob_observed is an matrix, NA where the cell is
missing: for every observed categorical cell, the posterior probability of its
own level computed as if the cell were missing, without a refit. A small value
points at a miscoded cell; the estimation does not use it. It is NA in
every column of a row above the combination cap as well, since such a row has
no pseudo-rows to compute it from. Under per-level detection it is not on the
same scale as cat_posterior: the diagnostic keeps 7.5.0's un-penalised
Gaussian density, evaluated at the returned (mixture) W, while the fit's
own posteriors now come from the cellwise-penalised per-candidate score
(.gloc_cat_score). Per-level scoring of observed cells is deliberately
deferred, so compare a value of this matrix with other values of it and with
the same fit's flagging rate, not with an entry of cat_posterior.
cat_multi_missing is the share of rows with two or more missing
categorical cells. cat_priors holds the final multinomial prior models,
so that level posteriors for other rows can be computed under this fit (for
example in bootstrap multiple imputation). All four are NULL under
categorical = "level", and under "em" when the data have no
categorical column.
em_starts is NULL unless the fit ran from two starts (see
categorical). Then it is a list: chosen, "complete" for
the first start or "na_level" for the second; objective,
converged and iterations, each a vector named complete
and na_level; and lambda, the penalty per continuous variable
in the objective. When the second start failed, its three entries are
NA and error holds its error message. iterations,
converged and criterion of the fit are those of the chosen run.
criterion is the named vector (means, scatter, weights,
scatter_spread, categorical): the three stopping residuals as of the last
iteration, compared against eps, plus the elementwise spread of
over the last .gloc_stall_iters iterations relative to its
largest variance. scatter_spread is reported only when converged
is FALSE, and is NA otherwise: on a converged fit the window
still holds the last steps of the approach, so a value there would say nothing
about stability. When the fit did not converge it says how much the returned
scatter depends on where maxit happened to stop – a settled cycle
reports its amplitude, a run still drifting reports the drift – and a caller
can test it instead of parsing a warning string. The fifth entry,
categorical, is the largest change of a categorical posterior
probability in the last iteration; it is 0 without the EM, NA when no
iteration ran, and part of the stopping rule with the EM. Under per-level
detection weights is taken over the candidates: the largest change of a
candidate's cell weight times the candidate's posterior probability (1 for a
row that is a single candidate or lies above the combination cap), divided by
the relaxation factor. The adaptive relaxation and the stall detector use the
same number, so a candidate the posterior has all but ruled out cannot hold up
convergence.
It does not tell those two apart, and it is not an error estimate. On 10
non-converged weights = "binary" fits it was positive for all 10,
while raising maxit left 8 of them bit-identical and moved 2 (by
0.008 and 0.096 relative, the latter matching its reported spread
exactly). That is the intended behaviour – all 10 return a scatter that
depends on the stopping point – but the rank correlation with what
raising maxit actually does is only 0.16, so read it as "this
answer is not settled", never as "it would move by this much".
Every entry is NA at maxit = 0.
Raymaekers, J. and Rousseeuw, P. J. (2024). The cellwise minimum covariance determinant estimator. JASA 119(548), 2610-2621. doi:10.1080/01621459.2023.2267777
Rousseeuw, P. J. (2026). Analyzing cellwise weighted data. Econometrics and Statistics 38, 31-41. doi:10.1016/j.ecosta.2023.01.007
Extends IRMI (Templ, Kowarik, and Filzmoser, 2011) with cellwise contamination handling. Each conditional regression uses a cell-weighted IRWLS engine where per-cell weights in the design matrix downweight contaminated cells without discarding entire observations.
imputeCellIRMI( data, method = "tukey", alpha = NULL, maxit = 100, maxit_irwls = 50, eps = 0.005, eps_irwls = 1e-06, uncert = "pmm", weight_update = "multivariate", init_weights = "ddc", hard_threshold = 0.5, trace = FALSE )imputeCellIRMI( data, method = "tukey", alpha = NULL, maxit = 100, maxit_irwls = 50, eps = 0.005, eps_irwls = 1e-06, uncert = "pmm", weight_update = "multivariate", init_weights = "ddc", hard_threshold = 0.5, trace = FALSE )
data |
a |
method |
weight function: |
alpha |
tuning constant. |
maxit |
maximum number of outer IRMI iterations (default: 100). |
maxit_irwls |
maximum number of inner IRWLS iterations per regression (default: 50). |
eps |
convergence tolerance for the outer loop (default: 5e-3). Convergence is declared when the relative change in imputed values falls below this threshold. |
eps_irwls |
convergence tolerance for the inner IRWLS (default: 1e-6). |
uncert |
imputation uncertainty method: |
weight_update |
strategy for updating cell weights between outer
iterations: |
init_weights |
method for initialising cell weights, one of
|
hard_threshold |
numeric in |
trace |
logical; if |
The algorithm works iteratively: in each outer iteration, every variable
with missing values is used as response in a conditional regression on
all remaining variables. For continuous responses, the custom
cellIRWLS() engine fits a weighted regression where each cell in
the design matrix receives its own weight reflecting potential cellwise
contamination. For categorical responses, a weighted multinomial model
is used. After each regression, cell weights for the response variable
are updated from the residuals.
The algorithm proceeds as follows:
Missing values are initialised using initialise.
Initial cell weights are computed with cellWeights() on
all continuous variables in the initialised data.
Outer loop (up to maxit iterations):
For each variable with missing values:
Form predictor matrix (all other variables) and
response (variable ).
If is continuous: fit cellIRWLS(X, y,
w_cell, w_response) and impute missing values in
using the fitted model plus uncertainty.
If is categorical: fit nnet::multinom()
with row weights derived from the cell weight matrix and
impute by sampling from predicted probabilities.
Update cell weights for from residuals via
cellWeightsFromResiduals().
Check convergence: relative change in imputed values
falls below eps.
A list with components:
data_imputed |
the imputed |
cellweights |
|
converged |
logical indicating whether the outer loop converged. |
iterations |
number of outer iterations used. |
Matthias Templ
Templ, M., Kowarik, A. and Filzmoser, P. (2011). Iterative stepwise regression imputation using standard and robust methods. Computational Statistics & Data Analysis, 55(10), 2793–2806.
imputeCellM, imputeCellEM,
initialise, irmi
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep, package = "VIM") result <- imputeCellIRMI(sleep) head(result$data_imputed) image(result$cellweights, main = "Cell weights") # With Huber weights (less aggressive downweighting) result2 <- imputeCellIRMI(sleep, method = "huber", trace = TRUE) # Mixed data example data(testdata) result3 <- imputeCellIRMI(testdata$wna)data(sleep, package = "VIM") result <- imputeCellIRMI(sleep) head(result$data_imputed) image(result$cellweights, main = "Cell weights") # With Huber weights (less aggressive downweighting) result2 <- imputeCellIRMI(sleep, method = "huber", trace = TRUE) # Mixed data example data(testdata) result3 <- imputeCellIRMI(testdata$wna)
Impute missing values using a cell-weighted M-estimation approach. Each cell in the predictor matrix receives its own weight reflecting potential cellwise contamination, so that contaminated predictor cells are downweighted without discarding entire observations.
imputeCellM( formula, data, method = "tukey", alpha = NULL, maxit_irwls = 50, eps_irwls = 1e-06, uncert = "pmm", value_back = "all", maxit = 10, eps = 0.005, trace = FALSE )imputeCellM( formula, data, method = "tukey", alpha = NULL, maxit_irwls = 50, eps_irwls = 1e-06, uncert = "pmm", value_back = "all", maxit = 10, eps = 0.005, trace = FALSE )
formula |
a model formula (e.g., |
data |
data.frame containing the data (formula interface only). |
method |
weight function: |
alpha |
tuning constant. |
maxit_irwls |
maximum IRWLS iterations (default: 50). |
eps_irwls |
convergence tolerance for IRWLS (default: 1e-6). |
uncert |
imputation uncertainty method: |
value_back |
|
maxit |
maximum number of chained-equation sweeps (data.frame interface only; default: 10). |
eps |
convergence tolerance for the chained sweeps (data.frame interface only; default: 5e-3). Convergence is declared when the relative change in imputed values falls below this threshold. |
trace |
logical; if |
The function has two interfaces: with a model formula, a single response
variable is imputed from the specified predictors; with a
data.frame (or matrix) as first argument, all variables with
missing values are imputed by chained equations, i.e. each such variable
is regressed on all remaining variables and the sweeps are iterated
until the imputed values stabilise.
The formula interface is a lightweight single-response alternative to
imputeCellIRMI. It fits one cell-weighted IRWLS regression
using cellIRWLS() and imputes the missing values in the response
variable. This is appropriate when only one variable needs imputation
and a specific model formula is desired.
The data.frame interface runs the same per-variable machinery as a
chained-equations algorithm: missing values are initialised
(median/mode), then each variable with missing values in turn is used as
response in a formula containing all remaining variables. Sweeps use
deterministic predictions and are iterated until the relative change of
the imputed values falls below eps (or maxit is reached);
the requested uncert step is applied once after convergence.
For categorical response variables, a weighted multinomial model via
multinom is fitted instead. Categorical predictors
are not subject to the cellwise contamination model (their cell weights
are always 1).
If value_back = "ymiss", a named vector of imputed values
(for rows that were originally missing) is returned. Otherwise, a list
with components:
the imputed data.frame (same structure as input)
n x p matrix of final cell weights (1 = clean, 0 = fully downweighted). Categorical columns always have weight 1.
logical; always TRUE for single-formula
imputation, convergence of the sweeps for the data.frame interface
integer; always 1L for single-formula
imputation, the number of sweeps for the data.frame interface
Model uncertainty via bootstrap (Rubin's combining rules for multiple imputation) is not yet implemented. The current version provides single imputation with stochastic uncertainty (PMM or residual draw). For valid multiple imputation, call the function repeatedly with different seeds and combine using Rubin's rules.
Matthias Templ
M. Templ, A. Kowarik, P. Filzmoser (2011) Iterative stepwise regression imputation using standard and robust methods. Computational Statistics & Data Analysis, Vol. 55, pp. 2793-2806.
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep, package = "VIM") # Impute Dream using BodyWgt and BrainWgt as predictors result <- imputeCellM(Dream ~ BodyWgt + BrainWgt, data = sleep) head(result) # Return only imputed values impvals <- imputeCellM(Dream ~ BodyWgt + BrainWgt, data = sleep, value_back = "ymiss") # Huber weights (less aggressive downweighting) result2 <- imputeCellM(Dream ~ BodyWgt + BrainWgt, data = sleep, method = "huber") # Chained-equations interface: impute all variables with missings result3 <- imputeCellM(sleep) head(result3$data_imputed)data(sleep, package = "VIM") # Impute Dream using BodyWgt and BrainWgt as predictors result <- imputeCellM(Dream ~ BodyWgt + BrainWgt, data = sleep) head(result) # Return only imputed values impvals <- imputeCellM(Dream ~ BodyWgt + BrainWgt, data = sleep, value_back = "ymiss") # Huber weights (less aggressive downweighting) result2 <- imputeCellM(Dream ~ BodyWgt + BrainWgt, data = sleep, method = "huber") # Chained-equations interface: impute all variables with missings result3 <- imputeCellM(sleep) head(result3$data_imputed)
Extends the cellwise MCD approach (Raymaekers & Rousseeuw 2024) to mixed continuous + categorical data. Uses MCD for robust covariance estimation of the continuous block, computes cellwise weights from conditional residuals, then imputes missing values via conditional expectations (continuous) and weighted multinomial regression (categorical). Iterates until convergence.
imputeCellMCD( data, maxit = 50, eps = 0.005, method = "tukey", alpha = NULL, mcd_alpha = 0.75, hard_threshold = 0.5, mcd_observed = "all", init_method = "median", uncert = "conditional", m = 1L, boot = FALSE, trace = FALSE )imputeCellMCD( data, maxit = 50, eps = 0.005, method = "tukey", alpha = NULL, mcd_alpha = 0.75, hard_threshold = 0.5, mcd_observed = "all", init_method = "median", uncert = "conditional", m = 1L, boot = FALSE, trace = FALSE )
data |
a |
maxit |
maximum number of iterations (default: 50). |
eps |
convergence tolerance (default: 5e-3). |
method |
weight function for cell weights: |
alpha |
tuning constant. |
mcd_alpha |
MCD concentration parameter (default: 0.75). |
hard_threshold |
numeric in |
mcd_observed |
strategy for covariance estimation:
|
init_method |
initialisation for missing values before iteration:
|
uncert |
imputation uncertainty: |
m |
number of multiple imputations (default: 1). If |
boot |
logical; intended to add bootstrap parameter uncertainty across
the |
trace |
logical; if |
A list with components:
data_imputed |
the imputed |
cellweights |
|
mu |
robust location estimate (continuous variables). |
Sigma |
robust covariance estimate (continuous variables). |
converged |
logical indicating convergence. |
iterations |
number of iterations performed. |
Multiple imputation with proper parameter-uncertainty propagation is
not yet implemented for this method (see boot). m > 1 returns
repeated imputations whose between-imputation variability comes only from
the stochastic uncertainty step (uncert) and estimator randomness,
so downstream Rubin pooling understates total variance. Treat the current
m > 1 output as approximate.
Matthias Templ
Raymaekers, J. and Rousseeuw, P.J. (2024). The cellwise minimum covariance determinant estimator. Journal of the American Statistical Association, 119(548), 2610–2621.
imputeCellIRMI, imputeCellM,
imputeCellEM
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
## Not run: data(sleep, package = "VIM") result <- imputeCellMCD(sleep) head(result$data_imputed) # Inspect cell weights image(result$cellweights, main = "Cell weights") # With pairwise robust covariance result2 <- imputeCellMCD(sleep, mcd_observed = "pairwise", trace = TRUE) ## End(Not run)## Not run: data(sleep, package = "VIM") result <- imputeCellMCD(sleep) head(result$data_imputed) # Inspect cell weights image(result$cellweights, main = "Cell weights") # With pairwise robust covariance result2 <- imputeCellMCD(sleep, mcd_observed = "pairwise", trace = TRUE) ## End(Not run)
Uses a cell-weighted MM-estimator for each variable regression: S-step on unweighted data (high breakdown), M-step with cell weights (fine-grained downweighting). This preserves the S-estimator's breakdown guarantee while incorporating cellwise information.
imputeCellMM( data, maxit = 50, eps = 0.005, alpha_weight = 4.685, init_weights = "mcd", uncert = "pmm", trace = FALSE )imputeCellMM( data, maxit = 50, eps = 0.005, alpha_weight = 4.685, init_weights = "mcd", uncert = "pmm", trace = FALSE )
data |
data.frame with missing values |
maxit |
maximum outer IRMI iterations (default: 50) |
eps |
convergence tolerance (default: 5e-3) |
alpha_weight |
tuning constant for bisquare cell weights (default: 4.685) |
init_weights |
initial cell weight method: |
uncert |
uncertainty method: |
trace |
logical |
list with data_imputed, cellweights, converged, iterations
Matthias Templ
IRMI-style imputation using cellwise-robust regression as the inner engine. Three engines are available: CRM (Filzmoser et al. 2020), Shooting S (Öllerer et al. 2016), and a cellwise-weighted MM hybrid.
imputeCellReg( data, engine = "crm", maxit = 50, eps = 0.005, uncert = "pmm", trace = FALSE )imputeCellReg( data, engine = "crm", maxit = 50, eps = 0.005, uncert = "pmm", trace = FALSE )
data |
data.frame with missing values (mixed continuous + categorical) |
engine |
regression engine: |
maxit |
maximum outer IRMI iterations (default: 50) |
eps |
convergence tolerance (default: 5e-3) |
uncert |
imputation uncertainty: |
trace |
logical; print progress |
The function cycles through all variables with missing values
(IRMI framework), fitting a cellwise-robust regression of each
variable on all others. The engine argument selects the
regression method:
"crm"CRM (Cellwise Robust M-regression) from the
crmReg package. Uses SPADIMO for cellwise outlier
detection within each regression. Requires crmReg.
"cellwise-mm"Hybrid: compute cell weights via MCD
conditional residuals, then fit MM-estimation (lmrob)
with row weights derived from cell weights. The MM-estimator
provides high breakdown point.
"shooting-s"Shooting S-estimator (Öllerer et al. 2016). Iterates between cellwise detection and S-estimation. Implemented from the published algorithm.
Categorical variables are imputed via weighted multinomial logistic regression, with row weights derived from the continuous cell weights.
A list with components:
data_imputed |
the imputed data.frame |
cellweights |
n x p matrix of cell weights (1 = clean) |
converged |
logical |
iterations |
number of outer iterations |
Matthias Templ
P. Filzmoser, S. Höppner, I. Ortner, S. Serneels, S. Van Aelst (2020) Cellwise robust M regression. Computational Statistics and Data Analysis, 147, 106944.
V. Öllerer, A. Alfons, C. Croux (2016) The shooting S-estimator for robust regression. Computational Statistics, 31(3), 829–844.
Convenience wrapper that dispatches to one of the three cellwise-robust
imputation methods: imputeCellIRMI, imputeCellM,
or imputeCellEM.
imputeCellwise(data, method = c("cellIRMI", "cellM", "cellEM"), ...)imputeCellwise(data, method = c("cellIRMI", "cellM", "cellEM"), ...)
data |
data.frame with missing values (mixed continuous + categorical). |
method |
imputation method: |
... |
additional arguments passed to the chosen method. |
The return value of the dispatched function. See the documentation of the individual methods for details.
Model uncertainty via bootstrap (Rubin's combining rules for multiple imputation) is not yet implemented. The current version provides single imputation with stochastic uncertainty (PMM or residual draw). For valid multiple imputation, call the function repeatedly with different seeds and combine using Rubin's rules.
Matthias Templ
imputeCellIRMI, imputeCellM,
imputeCellEM
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep, package = "VIM") result <- imputeCellwise(sleep, method = "cellIRMI") head(result$data_imputed)data(sleep, package = "VIM") result <- imputeCellwise(sleep, method = "cellIRMI") head(result$data_imputed)
Multiple imputation using classical and robust methods accounting for model and imputation uncertainty.
imputeRobust( form, data, boot = TRUE, robustboot = "stratified", method = "MM", takeAll = TRUE, alpha = 0.75, uncert = "pmm", family = "Gaussian", value_back = "all" )imputeRobust( form, data, boot = TRUE, robustboot = "stratified", method = "MM", takeAll = TRUE, alpha = 0.75, uncert = "pmm", family = "Gaussian", value_back = "all" )
form |
Model formulas as a list. |
data |
Data set to impute |
boot |
Accounting for model uncertainty with a classical bootstrap, Default: TRUE |
robustboot |
Accounting for model uncertainty with robust bootstrap methods, Default: 'stratified' |
method |
Imputation method, Default: 'MM' |
takeAll |
Missing values are intialized when TRUE, Default: TRUE |
alpha |
Relative size of good data points. Used for the robust bootstrap methods, Default: 0.75 |
uncert |
Imputation uncertainty method, Default: 'pmm' |
family |
Not supported and ignored. Foreseen for future versions, Default: 'Gaussian' |
value_back |
Only observations with imputed values as return object (ymiss), or the whole data set, Default: 'all' |
Complex formulas can be provided for each variable in your data set.
Imputed data set.
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
## Not run: if(interactive()){ #EXAMPLE1 } ## End(Not run)## Not run: if(interactive()){ #EXAMPLE1 } ## End(Not run)
FUNCTION_DESCRIPTION
imputeRobustChain( formulas = vector("list", ncol(data)), data, boot = TRUE, robustboot = TRUE, method = "lts", multinom.method = "multinom", takeAll = TRUE, eps = 0.5, maxit = 4, alpha = 0.5, uncert = "pmm", familiy = "Gaussian", value_back = "matrix", trace = FALSE )imputeRobustChain( formulas = vector("list", ncol(data)), data, boot = TRUE, robustboot = TRUE, method = "lts", multinom.method = "multinom", takeAll = TRUE, eps = 0.5, maxit = 4, alpha = 0.5, uncert = "pmm", familiy = "Gaussian", value_back = "matrix", trace = FALSE )
formulas |
PARAM_DESCRIPTION, Default: vector("list", ncol(data)) |
data |
PARAM_DESCRIPTION |
boot |
PARAM_DESCRIPTION, Default: TRUE |
robustboot |
PARAM_DESCRIPTION, Default: TRUE |
method |
PARAM_DESCRIPTION, Default: 'lts' |
multinom.method |
PARAM_DESCRIPTION, Default: 'multinom' |
takeAll |
PARAM_DESCRIPTION, Default: TRUE |
eps |
PARAM_DESCRIPTION, Default: 0.5 |
maxit |
PARAM_DESCRIPTION, Default: 4 |
alpha |
PARAM_DESCRIPTION, Default: 0.5 |
uncert |
PARAM_DESCRIPTION, Default: 'pmm' |
familiy |
PARAM_DESCRIPTION, Default: 'Gaussian' |
value_back |
PARAM_DESCRIPTION, Default: 'matrix' |
trace |
PARAM_DESCRIPTION, Default: FALSE |
DETAILS
OUTPUT_DESCRIPTION
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
## Not run: if(interactive()){ #EXAMPLE1 } ## End(Not run)## Not run: if(interactive()){ #EXAMPLE1 } ## End(Not run)
Rough estimation of missing values in a vector according to its type.
initialise(x, mixed, method = "kNN", mixed.constant = NULL)initialise(x, mixed, method = "kNN", mixed.constant = NULL)
x |
a vector. |
mixed |
a character vector containing the names of variables of type mixed (semi-continous). |
method |
Method used for Initialization (median or kNN) |
mixed.constant |
vector with length equal to the number of semi-continuous variables specifying the point of the semi-continuous distribution with non-zero probability |
Missing values are imputed with the mean for vectors of class
"numeric", with the median for vectors of class "integer", and
with the mode for vectors of class "factor". Hence, x should
be prepared in the following way: assign class "numeric" to numeric
vectors, assign class "integer" to ordinal vectors, and assign class
"factor" to nominal or binary vectors.
the initialized vector.
The function is used internally by some imputation algorithms.
Matthias Templ, modifications by Andreas Alfons
In each step of the iteration, one variable is used as a response variable and the remaining variables serve as the regressors.
irmi( x, eps = 5, maxit = 100, mixed = NULL, mixed.constant = NULL, count = NULL, step = FALSE, robust = FALSE, takeAll = TRUE, noise = TRUE, noise.factor = 1, force = FALSE, robMethod = "lmrob", force.mixed = TRUE, mi = 1, addMixedFactors = FALSE, trace = FALSE, init.method = "kNN", modelFormulas = NULL, multinom.method = "multinom", imp_var = TRUE, imp_suffix = "imp" )irmi( x, eps = 5, maxit = 100, mixed = NULL, mixed.constant = NULL, count = NULL, step = FALSE, robust = FALSE, takeAll = TRUE, noise = TRUE, noise.factor = 1, force = FALSE, robMethod = "lmrob", force.mixed = TRUE, mi = 1, addMixedFactors = FALSE, trace = FALSE, init.method = "kNN", modelFormulas = NULL, multinom.method = "multinom", imp_var = TRUE, imp_suffix = "imp" )
x |
data.frame or matrix |
eps |
threshold for convergency |
maxit |
maximum number of iterations |
mixed |
column index of the semi-continuous variables |
mixed.constant |
vector with length equal to the number of semi-continuous variables specifying the point of the semi-continuous distribution with non-zero probability |
count |
column index of count variables |
step |
a stepwise model selection is applied when the parameter is set to TRUE |
robust |
if TRUE, robust regression methods will be applied |
takeAll |
takes information of (initialised) missings in the response as well for regression imputation. |
noise |
irmi has the option to add a random error term to the imputed values, this creates the possibility for multiple imputation. The error term has mean 0 and variance corresponding to the variance of the regression residuals. |
noise.factor |
amount of noise. |
force |
if TRUE, the algorithm tries to find a solution in any case, possible by using different robust methods automatically. |
robMethod |
regression method when the response is continuous. Default is
MM-regression with |
force.mixed |
if TRUE, the algorithm tries to find a solution in any case, possible by using different robust methods automatically. |
mi |
number of multiple imputations. |
addMixedFactors |
if TRUE add additional factor variable for each mixed variable as X variable in the regression |
trace |
Additional information about the iterations when trace equals TRUE. |
init.method |
Method for initialization of missing values (kNN or median) |
modelFormulas |
a named list with the name of variables for the rhs of the formulas, which must contain a rhs formula for each variable with missing values, it should look like 'list(y1=c("x1","x2"),y2=c("x1","x3"))“ if factor variables for the mixed variables should be created for the regression models |
multinom.method |
Method for estimating the multinomial models (current default and only available method is multinom) |
imp_var |
TRUE/FALSE if a TRUE/FALSE variables for each imputed variable should be created show the imputation status |
imp_suffix |
suffix for the TRUE/FALSE variables showing the imputation status |
The method works sequentially and iterative. The method can deal with a mixture of continuous, semi-continuous, ordinal and nominal variables including outliers.
A full description of the method can be found in the mentioned reference.
the imputed data set.
Deprecated: irmi() is considered legacy functionality.
For new projects, please use vimpute() instead, which provides
a more modern, flexible and robust imputation framework.
Matthias Templ, Alexander Kowarik
M. Templ, A. Kowarik, P. Filzmoser (2011) Iterative stepwise regression imputation using standard and robust methods. Computational Statistics & Data Analysis, Vol. 55, pp. 2793-2806.
A. Kowarik, M. Templ (2016) Imputation with R package VIM. Journal of Statistical Software, 74(7), 1-16.
M. Templ (2023) Visualization and Imputation of Missing Values. Springer Publishing. Series in Computational Statistics. Cham. Switzerland. 463 pages. DOI: 10.1007/978-3-031-30073-8
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep) irmi(sleep) data(testdata) imp_testdata1 <- irmi(testdata$wna, mixed = testdata$mixed) # mixed.constant != 0 (-10) testdata$wna$m1[testdata$wna$m1 == 0] <- -10 testdata$wna$m2 <- log(testdata$wna$m2 + 0.001) imp_testdata2 <- irmi( testdata$wna, mixed = testdata$mixed, mixed.constant = c(-10,log(0.001)) ) imp_testdata2$m2 <- exp(imp_testdata2$m2) - 0.001 #example with fixed formulas for the variables with missing form = list( NonD = c("BodyWgt", "BrainWgt"), Dream = c("BodyWgt", "BrainWgt"), Sleep = c("BrainWgt" ), Span = c("BodyWgt" ), Gest = c("BodyWgt", "BrainWgt") ) irmi(sleep, modelFormulas = form, trace = TRUE) # Example with ordered variable td <- testdata$wna td$c1 <- as.ordered(td$c1) irmi(td)data(sleep) irmi(sleep) data(testdata) imp_testdata1 <- irmi(testdata$wna, mixed = testdata$mixed) # mixed.constant != 0 (-10) testdata$wna$m1[testdata$wna$m1 == 0] <- -10 testdata$wna$m2 <- log(testdata$wna$m2 + 0.001) imp_testdata2 <- irmi( testdata$wna, mixed = testdata$mixed, mixed.constant = c(-10,log(0.001)) ) imp_testdata2$m2 <- exp(imp_testdata2$m2) - 0.001 #example with fixed formulas for the variables with missing form = list( NonD = c("BodyWgt", "BrainWgt"), Dream = c("BodyWgt", "BrainWgt"), Sleep = c("BrainWgt" ), Span = c("BodyWgt" ), Gest = c("BodyWgt", "BrainWgt") ) irmi(sleep, modelFormulas = form, trace = TRUE) # Example with ordered variable td <- testdata$wna td$c1 <- as.ordered(td$c1) irmi(td)
k-Nearest Neighbour Imputation based on a variation of the Gower Distance for numerical, categorical, ordered and semi-continous variables.
kNN( data, variable = colnames(data), k = 5, dist_var = colnames(data), weights = NULL, numFun = median, catFun = maxCat, makeNA = NULL, NAcond = NULL, impNA = TRUE, donorcond = NULL, mixed = vector(), mixed.constant = NULL, trace = FALSE, imp_var = TRUE, imp_suffix = "imp", addRF = FALSE, onlyRF = FALSE, addRandom = FALSE, useImputedDist = TRUE, weightDist = FALSE, methodStand = "range", ordFun = medianSamp )kNN( data, variable = colnames(data), k = 5, dist_var = colnames(data), weights = NULL, numFun = median, catFun = maxCat, makeNA = NULL, NAcond = NULL, impNA = TRUE, donorcond = NULL, mixed = vector(), mixed.constant = NULL, trace = FALSE, imp_var = TRUE, imp_suffix = "imp", addRF = FALSE, onlyRF = FALSE, addRandom = FALSE, useImputedDist = TRUE, weightDist = FALSE, methodStand = "range", ordFun = medianSamp )
data |
data.frame or matrix |
variable |
variables where missing values should be imputed |
k |
number of Nearest Neighbours used |
dist_var |
names or variables to be used for distance calculation |
weights |
weights for the variables for distance calculation.
If |
numFun |
function for aggregating the k Nearest Neighbours in the case of a numerical variable |
catFun |
function for aggregating the k Nearest Neighbours in the case of a categorical variable |
makeNA |
list of length equal to the number of variables, with values, that should be converted to NA for each variable |
NAcond |
list of length equal to the number of variables, with a condition for imputing a NA |
impNA |
TRUE/FALSE whether NA should be imputed |
donorcond |
list of length equal to the number of variables, with a donorcond condition as character string. e.g. a list element can be ">5" or c(">5","<10). If the list element for a variable is NULL no condition will be applied for this variable. |
mixed |
names of mixed variables |
mixed.constant |
vector with length equal to the number of semi-continuous variables specifying the point of the semi-continuous distribution with non-zero probability |
trace |
TRUE/FALSE if additional information about the imputation process should be printed |
imp_var |
TRUE/FALSE if a TRUE/FALSE variables for each imputed variable should be created show the imputation status |
imp_suffix |
suffix for the TRUE/FALSE variables showing the imputation status |
addRF |
TRUE/FALSE each variable will be modelled using random forest regression ( |
onlyRF |
TRUE/FALSE if TRUE only additional distance variables created from random forest regression will be used as distance variables. |
addRandom |
TRUE/FALSE if an additional random variable should be added for distance calculation |
useImputedDist |
TRUE/FALSE if an imputed value should be used for distance calculation for imputing another variable. Be aware that this results in a dependency on the ordering of the variables. |
weightDist |
TRUE/FALSE if the distances of the k nearest neighbours should be used as weights in the aggregation step |
methodStand |
either "range" or "iqr" to be used in the standardization of numeric vaiables in the gower distance |
ordFun |
function for aggregating the k Nearest Neighbours in the case of a ordered factor variable |
Numerical and semi-continuous (mixed) distance variables are standardised by
their range (or IQR, see methodStand) so that each variable contributes on
a comparable scale; for mixed variables the point mass (mixed.constant) is
excluded from the range estimate.
Missing values in the distance variables (dist_var) are handled with a
sentinel: after standardisation an NA is replaced by the maximum of the
pooled column plus one. As a consequence two records that are both missing
the same distance variable have distance 0 on that variable (they are treated
as identical there), while a record missing the variable and one observing it
contribute up to about twice a normal variable's share. In effect kNN is
drawn towards donors that share the recipient's pattern of missingness in the
distance variables; under a MAR mechanism this can select unrepresentative
donors. This departs from Gower's (1971) convention of omitting
non-comparable variables and renormalising the remaining weights. To limit
the effect, prefer dist_var variables with few or no missing values.
the imputed data set.
Alexander Kowarik, Statistik Austria
A. Kowarik, M. Templ (2016) Imputation with R package VIM. Journal of Statistical Software, 74(7), 1-16.
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep) kNN(sleep) library(laeken) kNN(sleep, numFun = weightedMean, weightDist=TRUE)data(sleep) kNN(sleep) library(laeken) kNN(sleep, numFun = weightedMean, weightDist=TRUE)
Coordinates of the Kola background map.
Kola Project (1993-1998)
Reimann, C., Filzmoser, P., Garrett, R.G. and Dutter, R. (2008) Statistical Data Analysis Explained: Applied Environmental Statistics with R. Wiley, 2008.
data(kola.background, package = "VIM") bgmap(kola.background)data(kola.background, package = "VIM") bgmap(kola.background)
A synthetic, non-confidential enterprise-level data set inspired by the Austrian Leistungs- und Strukturstatistik from reporting years 2021 onward.
A data frame with 10000 observations and 38 variables.
The variables cover the main dimensions described in the Statistik Austria standard documentation: economic activity, NUTS2 region, data source, employment structure, turnover, intermediate consumption, gross value added, personnel costs, gross operating surplus, and tangible investment.
The monetary variables are expressed in thousand euros. The observations are generated synthetically and do not contain real enterprise records. Companion validation rules are available as lse_synthetic_rules.
Statistik Austria, Standard-Dokumentation zur Leistungs- und Strukturstatistik ab 2021, https://www.statistik.at/fileadmin/shared/QM/Standarddokumentationen/U/std_u_ls_ab_2021.pdf
data(lse_synthetic) str(lse_synthetic)data(lse_synthetic) str(lse_synthetic)
Accounting, additional edit, and combined validation rules for
lse_synthetic. The rules are stored as plain data frames of rule text so
that the data set does not depend on the validate package; build the
corresponding validate::validator objects with
validate::validator(.data = lse_synthetic_rules$edit) before passing them
to vimpute(method = "restricted").
A named list with three data frames: accounting (36 rules),
extra (56 rules), and edit (92 rules, the combination of both). Each
has the columns
rule name (V01, V02, ...)
the rule as R code, as accepted by validate::validator(.data = )
data(lse_synthetic_rules) names(lse_synthetic_rules) head(lse_synthetic_rules$edit) if (requireNamespace("validate", quietly = TRUE)) { edit_rules <- validate::validator(.data = lse_synthetic_rules$edit) length(edit_rules) }data(lse_synthetic_rules) names(lse_synthetic_rules) head(lse_synthetic_rules$edit) if (requireNamespace("validate", quietly = TRUE)) { edit_rules <- validate::validator(.data = lse_synthetic_rules$edit) length(edit_rules) }
Amputation generator for simulation studies (the variable-wise counterpart
of mice::ampute()): takes complete data, sets a controlled share of
cells to NA under a chosen missingness mechanism, and returns the
amputed data together with an attr(., "where") indicator matrix that
plugs directly into evaluation(), nrmse() and
pfc():
makeMissing( data, prop = 0.1, mechanism = c("MCAR", "MAR", "MNAR"), vars = NULL, weights = NULL, seed = NULL )makeMissing( data, prop = 0.1, mechanism = c("MCAR", "MAR", "MNAR"), vars = NULL, weights = NULL, seed = NULL )
data |
A complete data.frame or data.table (no missing values). |
prop |
Proportion of cells set to missing per target variable, strictly between 0 and 1. |
mechanism |
One of |
vars |
Character vector of target variables to receive missing values. Default: all columns. |
weights |
Optional named numeric vector. For |
seed |
Optional single number: applied via |
amp <- makeMissing(dat, prop = 0.2, mechanism = "MAR") imp <- vimpute(amp) evaluation(dat, imp, m = attr(amp, "where"))
Mechanisms (applied per target variable, each receiving exactly
round(prop * nrow(data)) missing cells):
"MCAR"cells are drawn uniformly at random.
"MAR"the probability of a cell going missing grows with a
weighted score of the other (observed) variables: rows are
drawn with probabilities plogis(z) where z is the
standardized weighted sum of the driver columns. Default drivers: all
numeric columns except the target, with equal weights; use
weights to select drivers and directions (negative weights make
low driver values predictive of missingness).
"MNAR"as "MAR", but the score is the target's
own standardized values, so high values are more often missing
(a weights entry named after the target flips or scales the
direction). Numeric targets only.
With several target variables the scores are computed on the complete input, so each target's mechanism conditions on the pre-amputation values of its drivers.
The amputed data, classed like the input (data.frame in,
data.frame out; data.table in, data.table out), with attributes
"where" (logical indicator matrix of the introduced missings),
"mechanism" and "prop".
Matthias Templ
evaluation(), vimpute(), kNN()
data(sleep) complete_rows <- na.omit(sleep[, c("BodyWgt", "BrainWgt", "Sleep", "Span")]) amp <- makeMissing(complete_rows, prop = 0.2, mechanism = "MAR", vars = "Sleep", seed = 1) colSums(is.na(amp)) imp <- kNN(amp, imp_var = FALSE) evaluation(complete_rows, imp, m = attr(amp, "where"))data(sleep) complete_rows <- na.omit(sleep[, c("BodyWgt", "BrainWgt", "Sleep", "Span")]) amp <- makeMissing(complete_rows, prop = 0.2, mechanism = "MAR", vars = "Sleep", seed = 1) colSums(is.na(amp)) imp <- kNN(amp, imp_var = FALSE) evaluation(complete_rows, imp, m = attr(amp, "where"))
Map of observed and missing/imputed values.
mapMiss( x, coords, map, delimiter = NULL, selection = c("any", "all"), col = c("skyblue", "red", "orange"), alpha = NULL, pch = c(19, 15), col.map = grey(0.5), legend = TRUE, interactive = TRUE, ... )mapMiss( x, coords, map, delimiter = NULL, selection = c("any", "all"), col = c("skyblue", "red", "orange"), alpha = NULL, pch = c(19, 15), col.map = grey(0.5), legend = TRUE, interactive = TRUE, ... )
x |
a vector, matrix or |
coords |
a |
map |
a background map to be passed to |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
selection |
the selection method for displaying missing/imputed values
in the map. Possible values are |
col |
a vector of length three giving the colors to be used for observed, missing and imputed values. If a single color is supplied, it is used for all values. |
alpha |
a numeric value between 0 and 1 giving the level of
transparency of the colors, or |
pch |
a vector of length two giving the plot characters to be used for observed and missing/imputed values. If a single plot character is supplied, it will be used for both. |
col.map |
the color to be used for the background map. |
legend |
a logical indicating whether a legend should be plotted. |
interactive |
a logical indicating whether information about selected observations can be displayed interactively (see ‘Details’). |
... |
further graphical parameters to be passed to
|
If interactive=TRUE, detailed information for an observation can be
printed on the console by clicking on the corresponding point. Clicking in
a region that does not contain any points quits the interactive session.
Matthias Templ, Andreas Alfons, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
bgmap(), bubbleMiss(),
colormapMiss()
data(chorizonDL, package = "VIM") data(kola.background, package = "VIM") coo <- chorizonDL[, c("XCOO", "YCOO")] ## for missing values x <- chorizonDL[, c("As", "Bi")] mapMiss(x, coo, kola.background) ## for imputed values x_imp <- kNN(chorizonDL[, c("As", "Bi")]) mapMiss(x_imp, coo, kola.background, delimiter = "_imp")data(chorizonDL, package = "VIM") data(kola.background, package = "VIM") coo <- chorizonDL[, c("XCOO", "YCOO")] ## for missing values x <- chorizonDL[, c("As", "Bi")] mapMiss(x, coo, kola.background) ## for imputed values x_imp <- kNN(chorizonDL[, c("As", "Bi")]) mapMiss(x_imp, coo, kola.background, delimiter = "_imp")
Create a scatterplot matrix with information about missing/imputed values in the plot margins of each panel.
marginmatrix( x, delimiter = NULL, col = c("skyblue", "red", "red4", "orange", "orange4"), alpha = NULL, ... )marginmatrix( x, delimiter = NULL, col = c("skyblue", "red", "red4", "orange", "orange4"), alpha = NULL, ... )
x |
a matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
col |
a vector of length five giving the colors to be used in the marginplots in the off-diagonal panels. The first color is used for the scatterplot and the boxplots for the available data, the second/fourth color for the univariate scatterplots and boxplots for the missing/imputed values in one variable, and the third/fifth color for the frequency of missing/imputed values in both variables (see ‘Details’). If only one color is supplied, it is used for the bivariate and univariate scatterplots and the boxplots for missing/imputed values in one variable, whereas the boxplots for the available data are transparent. Else if two colors are supplied, the second one is recycled. |
alpha |
a numeric value between 0 and 1 giving the level of
transparency of the colors, or |
... |
further arguments and graphical parameters to be passed to
|
marginmatrix uses pairsVIM() with a panel function based
on marginplot().
The graphical parameter oma will be set unless supplied as an
argument.
Andreas Alfons, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
marginplot(), pairsVIM(),
scattmatrixMiss()
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(sleep, package = "VIM") ## for missing values x <- sleep[, 1:5] x[,c(1,2,4)] <- log10(x[,c(1,2,4)]) marginmatrix(x) ## for imputed values x_imp <- kNN(sleep[, 1:5]) x_imp[,c(1,2,4)] <- log10(x_imp[,c(1,2,4)]) marginmatrix(x_imp, delimiter = "_imp")data(sleep, package = "VIM") ## for missing values x <- sleep[, 1:5] x[,c(1,2,4)] <- log10(x[,c(1,2,4)]) marginmatrix(x) ## for imputed values x_imp <- kNN(sleep[, 1:5]) x_imp[,c(1,2,4)] <- log10(x_imp[,c(1,2,4)]) marginmatrix(x_imp, delimiter = "_imp")
In addition to a standard scatterplot, information about missing/imputed values is shown in the plot margins. Furthermore, imputed values are highlighted in the scatterplot.
marginplot( x, delimiter = NULL, col = c("skyblue", "red", "red4", "orange", "orange4"), alpha = NULL, pch = c(1, 16), cex = par("cex"), numbers = TRUE, cex.numbers = par("cex"), zeros = FALSE, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, ann = par("ann"), axes = TRUE, frame.plot = axes, ... )marginplot( x, delimiter = NULL, col = c("skyblue", "red", "red4", "orange", "orange4"), alpha = NULL, pch = c(1, 16), cex = par("cex"), numbers = TRUE, cex.numbers = par("cex"), zeros = FALSE, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, ann = par("ann"), axes = TRUE, frame.plot = axes, ... )
x |
a |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
col |
a vector of length five giving the colors to be used in the plot. The first color is used for the scatterplot and the boxplots for the available data. In case of missing values, the second color is taken for the univariate scatterplots and boxplots for missing values in one variable and the third for the frequency of missing/imputed values in both variables (see ‘Details’). Otherwise, in case of imputed values, the fourth color is used for the highlighting, the frequency, the univariate scatterplot and the boxplots of mputed values in the first variable and the fifth color for the same applied to the second variable. A black color is used for the highlighting and the frequency of imputed values in both variables instead. If only one color is supplied, it is used for the bivariate and univariate scatterplots and the boxplots for missing/imputed values in one variable, whereas the boxplots for the available data are transparent. Else if two colors are supplied, the second one is recycled. |
alpha |
a numeric value between 0 and 1 giving the level of
transparency of the colors, or |
pch |
a vector of length two giving the plot symbols to be used for the scatterplot and the univariate scatterplots. If a single plot character is supplied, it is used for the scatterplot and the default value will be used for the univariate scatterplots (see ‘Details’). |
cex |
the character expansion factor to be used for the bivariate and univariate scatterplots. |
numbers |
a logical indicating whether the frequencies of missing/imputed values should be displayed in the lower left of the plot (see ‘Details’). |
cex.numbers |
the character expansion factor to be used for the frequencies of the missing/imputed values. |
zeros |
a logical vector of length two indicating whether the variables
are semi-continuous, i.e., contain a considerable amount of zeros. If
|
xlim, ylim
|
axis limits. |
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
ann |
a logical indicating whether plot annotation ( |
axes |
a logical indicating whether both axes should be drawn on the
plot. Use graphical parameter |
frame.plot |
a logical indicating whether a box should be drawn around the plot. |
... |
further graphical parameters to be passed down (see
|
Boxplots for available and missing/imputed data, as well as univariate scatterplots for missing/imputed values in one variable are shown in the plot margins.
Imputed values in either of the variables are highlighted in the scatterplot.
Furthermore, the frequencies of the missing/imputed values can be displayed by a number (lower left of the plot). The number in the lower left corner is the number of observations that are missing/imputed in both variables.
Some of the argument names and positions have changed with versions
1.3 and 1.4 due to extended functionality and for more consistency with
other plot functions in VIM. For back compatibility, the argument
cex.text can still be supplied to ...{} and is handled
correctly. Nevertheless, it is deprecated and no longer documented. Use
cex.numbers instead.
Andreas Alfons, Matthias Templ, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(tao, package = "VIM") data(chorizonDL, package = "VIM") ## for missing values marginplot(tao[,c("Air.Temp", "Humidity")]) marginplot(log10(chorizonDL[,c("CaO", "Bi")])) ## for imputed values marginplot(kNN(tao[,c("Air.Temp", "Humidity")]), delimiter = "_imp") marginplot(kNN(log10(chorizonDL[,c("CaO", "Bi")])), delimiter = "_imp")data(tao, package = "VIM") data(chorizonDL, package = "VIM") ## for missing values marginplot(tao[,c("Air.Temp", "Humidity")]) marginplot(log10(chorizonDL[,c("CaO", "Bi")])) ## for imputed values marginplot(kNN(tao[,c("Air.Temp", "Humidity")]), delimiter = "_imp") marginplot(kNN(log10(chorizonDL[,c("CaO", "Bi")])), delimiter = "_imp")
Suitable donors are searched based on matching of the categorical variables. The variables are dropped in reversed order, so that the last element of 'match_var' is dropped first and the first element of the vector is dropped last.
matchImpute( data, variable = colnames(data)[!colnames(data) %in% match_var], match_var, imp_var = TRUE, imp_suffix = "imp" )matchImpute( data, variable = colnames(data)[!colnames(data) %in% match_var], match_var, imp_var = TRUE, imp_suffix = "imp" )
data |
data.frame, data.table or matrix |
variable |
variables to be imputed |
match_var |
variables used for matching |
imp_var |
TRUE/FALSE if a TRUE/FALSE variables for each imputed variable should be created show the imputation status |
imp_suffix |
suffix for the TRUE/FALSE variables showing the imputation status |
The method works by sampling values from the suitable donors.
the imputed data set.
Johannes Gussenbauer, Alexander Kowarik
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep,package="VIM") imp_data <- matchImpute(sleep,variable=c("NonD","Dream","Sleep","Span","Gest"), match_var=c("Exp","Danger")) data(testdata,package="VIM") imp_testdata1 <- matchImpute(testdata$wna,match_var=c("c1","c2","b1","b2")) dt <- data.table::data.table(testdata$wna) imp_testdata2 <- matchImpute(dt,match_var=c("c1","c2","b1","b2"))data(sleep,package="VIM") imp_data <- matchImpute(sleep,variable=c("NonD","Dream","Sleep","Span","Gest"), match_var=c("Exp","Danger")) data(testdata,package="VIM") imp_testdata1 <- matchImpute(testdata$wna,match_var=c("c1","c2","b1","b2")) dt <- data.table::data.table(testdata$wna) imp_testdata2 <- matchImpute(dt,match_var=c("c1","c2","b1","b2"))
Create a matrix plot, in which all cells of a data matrix are visualized by rectangles. Available data is coded according to a continuous color scheme, while missing/imputed data is visualized by a clearly distinguishable color.
matrixplot( x, delimiter = NULL, sortby = NULL, col = c("red", "orange"), fixup = TRUE, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, labels = axes, xpd = NULL, interactive = TRUE, ... )matrixplot( x, delimiter = NULL, sortby = NULL, col = c("red", "orange"), fixup = TRUE, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, labels = axes, xpd = NULL, interactive = TRUE, ... )
x |
a matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
sortby |
a numeric or character value specifying the variable to sort
the data matrix by, or |
col |
the colors to be used in the plot. RGB colors may be specified
as character strings or as objects of class " |
fixup |
a logical indicating whether the colors should be corrected to
valid RGB values (see |
xlim, ylim
|
axis limits. |
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
axes |
a logical indicating whether axes should be drawn on the plot. |
labels |
either a logical indicating whether labels should be plotted below each column, or a character vector giving the labels. |
xpd |
a logical indicating whether the rectangles should be allowed to
go outside the plot region. If |
interactive |
a logical indicating whether a variable to be used for sorting can be selected interactively (see ‘Details’). |
... |
for |
In a matrix plot, all cells of a data matrix are visualized by
rectangles. Available data is coded according to a continuous color scheme.
To compute the colors via interpolation, the variables are first scaled to
the interval between 0 and 1. Missing/imputed values can then be
visualized by a clearly distinguishable color. It is thereby possible to use
colors in the HCL or RGB color space. A simple way of
visualizing the magnitude of the available data is to apply a greyscale,
which has the advantage that missing/imputed values can easily be
distinguished by using a color such as red/orange. Note that -Inf
and Inf are always assigned the begin and end color, respectively, of
the continuous color scheme.
Additionally, the observations can be sorted by the magnitude of a selected
variable. If interactive is TRUE, clicking in a column
redraws the plot with observations sorted by the corresponding variable.
Clicking anywhere outside the plot region quits the interactive session.
This is a much more powerful extension to the function imagmiss
in the former CRAN package dprep.
iimagMiss is deprecated and may be omitted in future versions of
VIM. Use matrixplot instead.
Andreas Alfons, Matthias Templ, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(sleep, package = "VIM") ## for missing values x <- sleep[, -(8:10)] x[,c(1,2,4,6,7)] <- log10(x[,c(1,2,4,6,7)]) matrixplot(x, sortby = "BrainWgt") ## for imputed values x_imp <- kNN(sleep[, -(8:10)]) x_imp[,c(1,2,4,6,7)] <- log10(x_imp[,c(1,2,4,6,7)]) matrixplot(x_imp, delimiter = "_imp", sortby = "BrainWgt")data(sleep, package = "VIM") ## for missing values x <- sleep[, -(8:10)] x[,c(1,2,4,6,7)] <- log10(x[,c(1,2,4,6,7)]) matrixplot(x, sortby = "BrainWgt") ## for imputed values x_imp <- kNN(sleep[, -(8:10)]) x_imp[,c(1,2,4,6,7)] <- log10(x_imp[,c(1,2,4,6,7)]) matrixplot(x_imp, delimiter = "_imp", sortby = "BrainWgt")
The function maxCat chooses the level with the most occurrences and random if the maximum is not unique.
maxCat(x, weights = NULL)maxCat(x, weights = NULL)
x |
factor vector |
weights |
numeric vector providing weights for the observations in x |
The function medianSamp chooses the level as the median or randomly between two levels.
medianSamp(x, weights = NULL)medianSamp(x, weights = NULL)
x |
ordered factor vector |
weights |
numeric vector providing weights for the observations in x |
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
Create a mosaic plot with information about missing/imputed values.
mosaicMiss( x, delimiter = NULL, highlight = NULL, selection = c("any", "all"), plotvars = NULL, col = c("skyblue", "red", "orange"), labels = NULL, miss.labels = TRUE, ... )mosaicMiss( x, delimiter = NULL, highlight = NULL, selection = c("any", "all"), plotvars = NULL, col = c("skyblue", "red", "orange"), labels = NULL, miss.labels = TRUE, ... )
x |
a matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
highlight |
a vector giving the variables to be used for highlighting.
If |
selection |
the selection method for highlighting missing/imputed
values in multiple highlight variables. Possible values are |
plotvars |
a vector giving the categorical variables to be plotted. If
|
col |
a vector of length three giving the colors to be used for observed, missing and imputed data. If only one color is supplied, the tiles corresponding to observed data are transparent and the supplied color is used for highlighting. |
labels |
a list of arguments for the labeling function
|
miss.labels |
either a logical indicating whether labels should be plotted for observed and missing/imputed (highlighted) data, or a character vector giving the labels. |
... |
additional arguments to be passed to |
Mosaic plots are graphical representations of multi-way contingency tables. The frequencies of the different cells are visualized by area-proportional rectangles (tiles). Additional tiles are be used to display the frequencies of missing/imputed values. Furthermore, missing/imputed values in a certain variable or combination of variables can be highlighted in order to explore their structure.
An object of class "structable" is returned invisibly.
This function uses the highly flexible strucplot framework of
package vcd.
Andreas Alfons, modifications by Bernd Prantner
Meyer, D., Zeileis, A. and Hornik, K. (2006) The
strucplot framework: Visualizing multi-way contingency tables with
vcd. Journal of Statistical Software, 17 (3), 1–48.
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(sleep, package = "VIM") ## for missing values mosaicMiss(sleep, highlight = 4, plotvars = 8:10, miss.labels = FALSE) ## for imputed values mosaicMiss(kNN(sleep), highlight = 4, plotvars = 8:10, delimiter = "_imp", miss.labels = FALSE)data(sleep, package = "VIM") ## for missing values mosaicMiss(sleep, highlight = 4, plotvars = 8:10, miss.labels = FALSE) ## for imputed values mosaicMiss(kNN(sleep), highlight = 4, plotvars = 8:10, delimiter = "_imp", miss.labels = FALSE)
Answers "is my imputation model well calibrated?" without ground truth
(the analogue of Amelia::overimpute(), model-agnostic): the
observed cells of one variable are treated as missing – fold by
fold, so every observed cell is overimputed exactly once – and imputed
with draws multiple imputations via vimpute(). For each cell the
observed value is compared with the mean and a level interval of
its draws; a well-calibrated model covers roughly level of the
observed values. Any genuinely missing cells stay missing and are imputed
as part of the model, exactly as they would be in a real run.
overimpute(data, variable, ..., draws = 5, folds = 5, level = 0.9, seed = NULL) ## S3 method for class 'vimpute_overimpute' print(x, ...) ## S3 method for class 'vimpute_overimpute' plot(x, ...)overimpute(data, variable, ..., draws = 5, folds = 5, level = 0.9, seed = NULL) ## S3 method for class 'vimpute_overimpute' print(x, ...) ## S3 method for class 'vimpute_overimpute' plot(x, ...)
data |
Dataset with (possibly) missing values. |
variable |
Single column name: the numeric variable whose observed cells are overimputed. |
... |
Passed on to |
draws |
Number of multiple-imputation draws per cell (>= 2). |
folds |
Number of folds the observed cells are split into (each fold
is set missing and overimputed in one |
level |
Coverage level of the reported interval (default 0.9). |
seed |
Optional single number: applied via |
x |
A |
The ... arguments are passed on to vimpute(), so the diagnostic runs
for any method, spec, or grammar configuration – e.g.
overimpute(dat, "y", method = "robust") or
overimpute(dat, "y", spec = list(y = vs_ranger(num.trees = 300))).
Note the cost: folds x draws imputation runs; lower folds and
draws (the defaults are modest) or use a fast method for large data.
For a stochastic spread of the draws keep an uncertainty source switched
on (the default uncert = "pmm", or boot/uncert); with purely
deterministic settings all draws coincide and the intervals collapse.
A data.frame of class vimpute_overimpute with one row per
observed cell: row (row index in data), observed,
mean, lower, upper (quantiles of the draws at
level), and covered. Attributes: variable,
level, draws, folds. print() reports the
empirical coverage; plot() draws the observed-vs-imputed
calibration plot with intervals and the 45-degree line.
Matthias Templ
vimpute(), makeMissing(), evaluation()
## Not run: data(sleep) ov <- overimpute(sleep, "Sleep", method = "robust", sequential = FALSE, draws = 5, folds = 5, seed = 1) print(ov) # empirical coverage of the 90% intervals plot(ov) ## End(Not run)## Not run: data(sleep) ov <- overimpute(sleep, "Sleep", method = "robust", sequential = FALSE, draws = 5, folds = 5, seed = 1) print(ov) # empirical coverage of the 90% intervals plot(ov) ## End(Not run)
Create a scatterplot matrix.
pairsVIM( x, ..., delimiter = NULL, main = NULL, sub = NULL, panel = points, lower = panel, upper = panel, diagonal = NULL, labels = TRUE, pos.labels = NULL, cex.labels = NULL, font.labels = par("font"), layout = c("matrix", "graph"), gap = 1 )pairsVIM( x, ..., delimiter = NULL, main = NULL, sub = NULL, panel = points, lower = panel, upper = panel, diagonal = NULL, labels = TRUE, pos.labels = NULL, cex.labels = NULL, font.labels = par("font"), layout = c("matrix", "graph"), gap = 1 )
x |
a matrix or |
... |
further arguments and graphical parameters to be passed down.
|
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
main, sub
|
main and sub title. |
panel |
a |
lower, upper
|
separate panel functions to be used below and above the diagonal, respectively. |
diagonal |
optional |
labels |
either a logical indicating whether labels should be plotted in the diagonal panels, or a character vector giving the labels. |
pos.labels |
the vertical position of the labels in the diagonal panels. |
cex.labels |
the character expansion factor to be used for the labels. |
font.labels |
the font to be used for the labels. |
layout |
a character string giving the layout of the scatterplot
matrix. Possible values are |
gap |
a numeric value giving the distance between the panels in margin lines. |
This function is the workhorse for marginmatrix() and
scattmatrixMiss().
The graphical parameter oma will be set unless supplied as an
argument.
A panel function should not attempt to start a new plot, since the
coordinate system for each panel is set up by pairsVIM.
The code is based on graphics::pairs(). Starting with
version 1.4, infinite values are no longer removed before passing the
x and y vectors to the panel functions.
Andreas Alfons, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
marginmatrix(), scattmatrixMiss()
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(sleep, package = "VIM") x <- sleep[, -(8:10)] x[,c(1,2,4,6,7)] <- log10(x[,c(1,2,4,6,7)]) pairsVIM(x)data(sleep, package = "VIM") x <- sleep[, -(8:10)] x[,c(1,2,4,6,7)] <- log10(x[,c(1,2,4,6,7)]) pairsVIM(x)
Parallel coordinate plot with adjustments for missing/imputed values. Missing values in the plotted variables may be represented by a point above the corresponding coordinate axis to prevent disconnected lines. In addition, observations with missing/imputed values in selected variables may be highlighted.
parcoordMiss( x, delimiter = NULL, highlight = NULL, selection = c("any", "all"), plotvars = NULL, plotNA = TRUE, col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), alpha = NULL, lty = par("lty"), xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, labels = TRUE, xpd = NULL, interactive = TRUE, ... )parcoordMiss( x, delimiter = NULL, highlight = NULL, selection = c("any", "all"), plotvars = NULL, plotNA = TRUE, col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), alpha = NULL, lty = par("lty"), xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, labels = TRUE, xpd = NULL, interactive = TRUE, ... )
x |
a matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
highlight |
a vector giving the variables to be used for highlighting.
If |
selection |
the selection method for highlighting missing/imputed
values in multiple highlight variables. Possible values are |
plotvars |
a vector giving the variables to be plotted. If |
plotNA |
a logical indicating whether missing values in the plot variables should be represented by a point above the corresponding coordinate axis to prevent disconnected lines. |
col |
if |
alpha |
a numeric value between 0 and 1 giving the level of
transparency of the colors, or |
lty |
if |
xlim, ylim
|
axis limits. |
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
labels |
either a logical indicating whether labels should be plotted below each coordinate axis, or a character vector giving the labels. |
xpd |
a logical indicating whether the lines should be allowed to go
outside the plot region. If |
interactive |
a logical indicating whether interactive features should be enabled (see ‘Details’). |
... |
for |
In parallel coordinate plots, the variables are represented by parallel
axes. Each observation of the scaled data is shown as a line. Observations
with missing/imputed values in selected variables may thereby be
highlighted. However, plotting variables with missing values results in
disconnected lines, making it impossible to trace the respective
observations across the graph. As a remedy, missing values may be
represented by a point above the corresponding coordinate axis, which is
separated from the main plot by a small gap and a horizontal line, as
determined by plotNA. Connected lines can then be drawn for all
observations. Nevertheless, a caveat of this display is that it may draw
attention away from the main relationships between the variables.
If interactive is TRUE, it is possible switch between this
display and the standard display without the separate level for missing
values by clicking in the top margin of the plot. In addition, the variables
to be used for highlighting can be selected interactively. Observations
with missing/imputed values in any or in all of the selected variables are
highlighted (as determined by selection). A variable can be added to
the selection by clicking on a coordinate axis. If a variable is already
selected, clicking on its coordinate axis removes it from the selection.
Clicking anywhere outside the plot region (except the top margin, if
missing/imputed values exist) quits the interactive session.
Some of the argument names and positions have changed with versions
1.3 and 1.4 due to extended functionality and for more consistency with
other plot functions in VIM. For back compatibility, the arguments
colcomb and xaxlabels can still be supplied to ...{}
and are handled correctly. Nevertheless, they are deprecated and no longer
documented. Use highlight and labels instead.
Andreas Alfons, Matthias Templ, modifications by Bernd Prantner
Wegman, E. J. (1990) Hyperdimensional data analysis using parallel coordinates. Journal of the American Statistical Association 85 (411), 664–675.
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(chorizonDL, package = "VIM") ## for missing values parcoordMiss(chorizonDL[,c(15,101:110)], plotvars=2:11, interactive = FALSE) legend("top", col = c("skyblue", "red"), lwd = c(1,1), legend = c("observed in Bi", "missing in Bi")) ## for imputed values parcoordMiss(kNN(chorizonDL[,c(15,101:110)]), delimiter = "_imp" , plotvars=2:11, interactive = FALSE) legend("top", col = c("skyblue", "orange"), lwd = c(1,1), legend = c("observed in Bi", "imputed in Bi"))data(chorizonDL, package = "VIM") ## for missing values parcoordMiss(chorizonDL[,c(15,101:110)], plotvars=2:11, interactive = FALSE) legend("top", col = c("skyblue", "red"), lwd = c(1,1), legend = c("observed in Bi", "missing in Bi")) ## for imputed values parcoordMiss(kNN(chorizonDL[,c(15,101:110)]), delimiter = "_imp" , plotvars=2:11, interactive = FALSE) legend("top", col = c("skyblue", "orange"), lwd = c(1,1), legend = c("observed in Bi", "imputed in Bi"))
Boxplot of one variable of interest plus information about missing/imputed values in other variables.
pbox( x, delimiter = NULL, pos = 1, selection = c("none", "any", "all"), col = c("skyblue", "red", "red4", "orange", "orange4"), numbers = TRUE, cex.numbers = par("cex"), xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, frame.plot = axes, labels = axes, interactive = TRUE, ... )pbox( x, delimiter = NULL, pos = 1, selection = c("none", "any", "all"), col = c("skyblue", "red", "red4", "orange", "orange4"), numbers = TRUE, cex.numbers = par("cex"), xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, frame.plot = axes, labels = axes, interactive = TRUE, ... )
x |
a vector, matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
pos |
a numeric value giving the index of the variable of interest.
Additional variables in |
selection |
the selection method for grouping according to
missingness/number of imputed missings in multiple additional variables.
Possible values are |
col |
a vector of length five giving the colors to be used in the plot. The first color is used for the boxplots of the available data, the second/fourth are used for missing/imputed data, respectively, and the third/fifth color for the frequencies of missing/imputed values in both variables (see ‘Details’). If only one color is supplied, it is used for the boxplots for missing/imputed data, whereas the boxplots for the available data are transparent. Else if two colors are supplied, the second one is recycled. |
numbers |
a logical indicating whether the frequencies of missing/imputed values should be displayed (see ‘Details’). |
cex.numbers |
the character expansion factor to be used for the frequencies of the missing/imputed values. |
xlim, ylim
|
axis limits. |
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
axes |
a logical indicating whether axes should be drawn on the plot. |
frame.plot |
a logical indicating whether a box should be drawn around the plot. |
labels |
either a logical indicating whether labels should be plotted below each box, or a character vector giving the labels. |
interactive |
a logical indicating whether variables can be switched interactively (see ‘Details’). |
... |
for |
This plot consists of several boxplots. First, a standard boxplot of the
variable of interest is produced. Second, boxplots grouped by observed and
missing/imputed values according to selection are produced for the
variable of interest.
Additionally, the frequencies of the missing/imputed values can be represented by numbers. If so, the first line corresponds to the observed values of the variable of interest and their distribution in the different groups, the second line to the missing/imputed values.
If interactive=TRUE, clicking in the left margin of the plot results
in switching to the previous variable and clicking in the right margin
results in switching to the next variable. Clicking anywhere else on the
graphics device quits the interactive session.
a list as returned by graphics::boxplot().
Some of the argument names and positions have changed with version 1.3
due to extended functionality and for more consistency with other plot
functions in VIM. For back compatibility, the arguments names
and cex.text can still be supplied to ...{} and are handled
correctly. Nevertheless, they are deprecated and no longer documented. Use
labels and cex.numbers instead.
Andreas Alfons, Matthias Templ, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
scattJitt(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(chorizonDL, package = "VIM") ## for missing values pbox(log(chorizonDL[, c(4,5,8,10,11,16:17,19,25,29,37,38,40)])) ## for imputed values pbox(kNN(log(chorizonDL[, c(4,8,10,11,17,19,25,29,37,38,40)])), delimiter = "_imp")data(chorizonDL, package = "VIM") ## for missing values pbox(log(chorizonDL[, c(4,5,8,10,11,16:17,19,25,29,37,38,40)])) ## for imputed values pbox(kNN(log(chorizonDL[, c(4,8,10,11,17,19,25,29,37,38,40)])), delimiter = "_imp")
Draws mice-style multiple-imputation diagnostics for a vimmi
object, for every numeric variable with imputed cells:
"chains"convergence trace plots of the sequential (FCS)
imputation: the mean and the standard deviation of the imputed values
against the iteration number, one line per imputation. Chains that
mix well fluctuate around a common level without trends; systematic
drift suggests increasing nseq. Requires chain statistics
(stored by vimpute() since VIM 7.3.0).
"density"the density of the observed values (blue, bold)
overlaid with the density of each imputation's imputed values (red,
thin) – the analogue of mice::densityplot(). Imputed
densities that deviate wildly from the observed one can flag model
misfit (or genuine MAR shifts).
"strip"every value as a point: column 0 holds the
observed values (blue), columns 1..m the imputed values of each
imputation (red) – the analogue of mice::stripplot().
## S3 method for class 'vimmi' plot(x, y = c("chains", "density", "strip"), ...)## S3 method for class 'vimmi' plot(x, y = c("chains", "density", "strip"), ...)
x |
A |
y |
Type of diagnostic: |
... |
Passed on to the underlying base-graphics calls |
x, invisibly
## Not run: result <- vimpute(sleep, method = "ranger", m = 5, seed = 1) plot(result) # convergence chains plot(result, "density") # observed vs imputed densities plot(result, "strip") # observed vs imputed values ## End(Not run)## Not run: result <- vimpute(sleep, method = "ranger", m = 5, seed = 1) plot(result) # convergence chains plot(result, "density") # observed vs imputed densities plot(result, "strip") # observed vs imputed values ## End(Not run)
This function is used by the VIM GUI for transformation and
standardization of the data.
prepare( x, scaling = c("none", "classical", "MCD", "robust", "onestep"), transformation = c("none", "minus", "reciprocal", "logarithm", "exponential", "boxcox", "clr", "ilr", "alr"), alpha = NULL, powers = NULL, start = 0, alrVar )prepare( x, scaling = c("none", "classical", "MCD", "robust", "onestep"), transformation = c("none", "minus", "reciprocal", "logarithm", "exponential", "boxcox", "clr", "ilr", "alr"), alpha = NULL, powers = NULL, start = 0, alrVar )
x |
a vector, matrix or |
scaling |
the scaling to be applied to the data. Possible values are
|
transformation |
the transformation of the data. Possible values are
|
alpha |
a numeric parameter controlling the size of the subset for the
MCD (if |
powers |
a numeric vector giving the powers to be used in the Box-Cox
transformation (if |
start |
a constant to be added prior to Box-Cox transformation (if
|
alrVar |
variable to be used as denominator in the additive logratio
transformation (if |
Transformation:
"none": no transformation is used.
"logarithm": compute the the logarithm (to the base 10).
"boxcox": apply a Box-Cox transformation. Powers may be specified or
calculated with the function car::powerTransform().
Standardization:
"none": no standardization is used.
"classical": apply a z-Transformation on each variable by
using function scale().
"robust": apply a robustified z-Transformation by using median
and MAD.
Transformed and standardized data.
Matthias Templ, modifications by Andreas Alfons
scale(), car::powerTransform()
data(sleep, package = "VIM") x <- sleep[, c("BodyWgt", "BrainWgt")] prepare(x, scaling = "robust", transformation = "logarithm")data(sleep, package = "VIM") x <- sleep[, c("BodyWgt", "BrainWgt")] prepare(x, scaling = "robust", transformation = "logarithm")
Pulp quality by lignin content remaining
A data frame with 301 observations on the following 23 variables.
Pulp quality is measured by the lignin content remaining in the pulp: the Kappa number. This data set is used to understand which variables in the process influence the Kappa number, and if it can be predicted accurately enough for an inferential sensor application. Variables with a number at the end have been lagged by that number of hours to line up the data.
https://openmv.net/info/kamyr-digester
K. Walkush and R.R. Gustafson. Application of feedforward neural networks and partial least squares regression for modelling Kappa number in a continuous Kamyr digester", Pulp and Paper Canada, 95, 1994, p T7-T13.
data(pulplignin) str(pulplignin) aggr(pulplignin)data(pulplignin) str(pulplignin) aggr(pulplignin)
Impute missing values based on random-forest models via vimpute().
rangerImpute( formula, data, imp_var = TRUE, imp_suffix = "imp", ..., verbose = FALSE, median = FALSE )rangerImpute( formula, data, imp_var = TRUE, imp_suffix = "imp", ..., verbose = FALSE, median = FALSE )
formula |
model formula for the imputation |
data |
A |
imp_var |
|
imp_suffix |
suffix used for TF imputation variables |
... |
Additional ranger hyperparameters (e.g. |
verbose |
Show the number of observations used for training and evaluating the RF-Model. |
median |
|
the imputed data set.
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
regressionImp(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
data(sleep) # rangerImpute() runs on vimpute(), which VIM backs with the suggested # mlr3 stack -- skip the example where that stack is not installed. if (requireNamespace("mlr3", quietly = TRUE) && requireNamespace("mlr3learners", quietly = TRUE) && requireNamespace("mlr3pipelines", quietly = TRUE)) { rangerImpute(Dream+NonD~BodyWgt+BrainWgt,data=sleep) }data(sleep) # rangerImpute() runs on vimpute(), which VIM backs with the suggested # mlr3 stack -- skip the example where that stack is not installed. if (requireNamespace("mlr3", quietly = TRUE) && requireNamespace("mlr3learners", quietly = TRUE) && requireNamespace("mlr3pipelines", quietly = TRUE)) { rangerImpute(Dream+NonD~BodyWgt+BrainWgt,data=sleep) }
vimpute()
vimpute() resolves its method argument through a package-level method
registry. The built-in methods ("ranger", "xgboost", "regularized",
"robust", "gam", "robgam", "restricted") are pre-registered; this function adds
(or, with overwrite = TRUE, replaces) a user-defined method backed by any
pair of mlr3 learners – e.g. regr.rpart/classif.rpart from mlr3
itself, or learners from mlr3extralearners such as lightgbm – without
modifying VIM. After registration the new name can be used anywhere the
built-in method names work: as a global method, in a per-variable method
list, and in method-keyed learner_params.
register_vimpute_method( name, learner, packages = character(), setup = NULL, defaults = NULL, search_space = NULL, supports_formula = FALSE, fallback = "robust", validate = NULL, overwrite = FALSE )register_vimpute_method( name, learner, packages = character(), setup = NULL, defaults = NULL, search_space = NULL, supports_formula = FALSE, fallback = "robust", validate = NULL, overwrite = FALSE )
name |
Single character string: the method name to be used in
|
learner |
Named list with elements |
packages |
Character vector of packages that must be installed when the
method is used (checked with |
setup |
|
defaults |
|
search_space |
|
supports_formula |
Logical: can the method be used with the |
fallback |
Single method name used when |
validate |
|
overwrite |
Logical: replace an existing registration of the same name? Built-in methods can never be replaced. |
Uncertainty handling for registered methods: PMM (uncert = "pmm", the
default, and pmm = TRUE) and uncert = "midastouch" work with any
method because they only use the method's predictions.
uncert = "normalerror"/"resid" and boot = TRUE derive residuals from
training predictions when the model object does not expose them.
Invisibly, the registered method name.
vimpute_methods(), unregister_vimpute_method(), vimpute()
Other vimpute method registry:
unregister_vimpute_method(),
vimpute_methods()
# a CART method backed by mlr3's rpart learners -- one call, no VIM patching register_vimpute_method("cart", learner = list(regr = "regr.rpart", classif = "classif.rpart"), packages = "rpart") "cart" %in% vimpute_methods() data(sleep) res <- vimpute(sleep[, c("Sleep", "Dream", "Span")], method = "cart", sequential = FALSE) unregister_vimpute_method("cart")# a CART method backed by mlr3's rpart learners -- one call, no VIM patching register_vimpute_method("cart", learner = list(regr = "regr.rpart", classif = "classif.rpart"), packages = "rpart") "cart" %in% vimpute_methods() data(sleep) res <- vimpute(sleep[, c("Sleep", "Dream", "Span")], method = "cart", sequential = FALSE) unregister_vimpute_method("cart")
Impute missing values based on a regression / classification model.
regressionImp( formula, data, family = "AUTO", robust = FALSE, imp_var = TRUE, imp_suffix = "imp", mod_cat = FALSE )regressionImp( formula, data, family = "AUTO", robust = FALSE, imp_var = TRUE, imp_suffix = "imp", mod_cat = FALSE )
formula |
model formula to impute one variable |
data |
A data.frame containing the data |
family |
ignored in this wrapper version (only "AUTO"-like behaviour via vimpute) |
robust |
logical; if TRUE use method = "robust", otherwise "regularized" |
imp_var |
logical; if TRUE create TRUE/FALSE variables indicating imputation status |
imp_suffix |
suffix used for TF imputation variables |
mod_cat |
ignored in this wrapper version (classification handled by vimpute) |
By default (lm() for numeric responses and glm() for binary responses,
with any number of predictors) the imputation is deterministic and matches a
plain regression fit. When the design is rank-deficient (collinear predictors
or ) or the response is a multi-level factor, it falls back to
the regularized (glmnet) path via vimpute() with method = "regularized".
If robust = TRUE, vimpute() with method = "robust"
(lmrob() / glmrob()) is used.
the imputed data set (same class as data)
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
sampleCat(),
vimmi,
vimpute(),
xgboostImpute()
Add a rug representation of missing/imputed values in only one of the variables to scatterplots.
rugNA( x, y, ticksize = NULL, side = 1, col = "red", alpha = NULL, miss = NULL, lwd = 0.5, ... )rugNA( x, y, ticksize = NULL, side = 1, col = "red", alpha = NULL, miss = NULL, lwd = 0.5, ... )
x, y
|
numeric vectors. |
ticksize |
the length of the ticks. Positive lengths give inward ticks. |
side |
an integer giving the side of the plot to draw the rug representation. |
col |
the color to be used for the ticks. |
alpha |
the alpha value (between 0 and 1). |
miss |
a |
lwd |
the line width to be used for the ticks. |
... |
further arguments to be passed to |
If side is 1 or 3, the rug representation consists of values
available in x but missing/imputed in y. Else if side
is 2 or 4, it consists of values available in y but missing/imputed
in x.
Andreas Alfons, modifications by Bernd Prantner
data(tao, package = "VIM") ## for missing values x <- tao[, "Air.Temp"] y <- tao[, "Humidity"] plot(x, y) rugNA(x, y, side = 1) rugNA(x, y, side = 2) ## for imputed values x_imp <- kNN(tao[, c("Air.Temp","Humidity")]) x <- x_imp[, "Air.Temp"] y <- x_imp[, "Humidity"] miss <- x_imp[, c("Air.Temp_imp","Humidity_imp")] plot(x, y) rugNA(x, y, side = 1, col = "orange", miss = miss) rugNA(x, y, side = 2, col = "orange", miss = miss)data(tao, package = "VIM") ## for missing values x <- tao[, "Air.Temp"] y <- tao[, "Humidity"] plot(x, y) rugNA(x, y, side = 1) rugNA(x, y, side = 2) ## for imputed values x_imp <- kNN(tao[, c("Air.Temp","Humidity")]) x <- x_imp[, "Air.Temp"] y <- x_imp[, "Humidity"] miss <- x_imp[, c("Air.Temp_imp","Humidity_imp")] plot(x, y) rugNA(x, y, side = 1, col = "orange", miss = miss) rugNA(x, y, side = 2, col = "orange", miss = miss)
The function sampleCat samples with probabilites corresponding to the occurrence of the level in the NNs.
sampleCat(x, weights = NULL)sampleCat(x, weights = NULL)
x |
factor vector |
weights |
numeric vector providing weights for the observations in x |
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
vimmi,
vimpute(),
xgboostImpute()
Synthetic subset of the Austrian structural business statistics (SBS) data, namely NACE code 52.42 (retail sale of clothing).
The Austrian SBS data set consists of more than 320.000 enterprises. Available raw (unedited) data set: 21669 observations in 90 variables, structured according NACE revision 1.1 with 3891 missing values.
We investigate 9 variables of NACE 52.42 (retail sale of clothing).
From these confidential raw data set a non-confidential, close-to-reality, synthetic data set was generated.
data(SBS5242) aggr(SBS5242)data(SBS5242) aggr(SBS5242)
Create a bivariate jitter plot.
scattJitt( x, delimiter = NULL, col = c("skyblue", "red", "red4", "orange", "orange4"), alpha = NULL, cex = par("cex"), col.line = "lightgrey", lty = "dashed", lwd = par("lwd"), numbers = TRUE, cex.numbers = par("cex"), main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, frame.plot = axes, labels = c("observed", "missing", "imputed"), ... )scattJitt( x, delimiter = NULL, col = c("skyblue", "red", "red4", "orange", "orange4"), alpha = NULL, cex = par("cex"), col.line = "lightgrey", lty = "dashed", lwd = par("lwd"), numbers = TRUE, cex.numbers = par("cex"), main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, frame.plot = axes, labels = c("observed", "missing", "imputed"), ... )
x |
a |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
col |
a vector of length five giving the colors to be used in the plot. The first color will be used for complete observations, the second/fourth color for missing/imputed values in only one variable, and the third/fifth color for missing/imputed values in both variables. If only one color is supplied, it is used for all. Else if two colors are supplied, the second one is recycled. |
alpha |
a numeric value between 0 and 1 giving the level of
transparency of the colors, or |
cex |
the character expansion factor for the plot characters. |
col.line |
the color for the lines dividing the plot region. |
lty |
the line type for the lines dividing the plot region (see
|
lwd |
the line width for the lines dividing the plot region. |
numbers |
a logical indicating whether the frequencies of observed and missing/imputed values should be displayed (see ‘Details’). |
cex.numbers |
the character expansion factor to be used for the frequencies of the observed and missing/imputed values. |
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
axes |
a logical indicating whether both axes should be drawn on the
plot. Use graphical parameter |
frame.plot |
a logical indicating whether a box should be drawn around the plot. |
labels |
a vector of length three giving the axis labels for the regions for observed, missing and imputed values (see ‘Details’). |
... |
further graphical parameters to be passed down (see
|
The amount of observed and missing/imputed values is visualized by jittered points. Thereby the plot region is divided into up to four regions according to the existence of missing/imputed values in one or both variables. In addition, the amount of observed and missing/imputed values can be represented by a number.
Some of the argument names and positions have changed with version 1.3
due to extended functionality and for more consistency with other plot
functions in VIM. For back compatibility, the argument
cex.text can still be supplied to ...{} and is handled
correctly. Nevertheless, it is deprecated and no longer documented. Use
cex.numbers instead.
Matthias Templ, modifications by Andreas Alfons and Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattMiss(),
scattmatrixMiss(),
spineMiss()
data(tao, package = "VIM") ## for missing values scattJitt(tao[, c("Air.Temp", "Humidity")]) ## for imputed values scattJitt(kNN(tao[, c("Air.Temp", "Humidity")]), delimiter = "_imp")data(tao, package = "VIM") ## for missing values scattJitt(tao[, c("Air.Temp", "Humidity")]) ## for imputed values scattJitt(kNN(tao[, c("Air.Temp", "Humidity")]), delimiter = "_imp")
Scatterplot matrix in which observations with missing/imputed values in certain variables are highlighted.
scattmatrixMiss( x, delimiter = NULL, highlight = NULL, selection = c("any", "all"), plotvars = NULL, col = c("skyblue", "red", "orange"), alpha = NULL, pch = c(1, 3), lty = par("lty"), diagonal = c("density", "none"), interactive = TRUE, ... )scattmatrixMiss( x, delimiter = NULL, highlight = NULL, selection = c("any", "all"), plotvars = NULL, col = c("skyblue", "red", "orange"), alpha = NULL, pch = c(1, 3), lty = par("lty"), diagonal = c("density", "none"), interactive = TRUE, ... )
x |
a matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
highlight |
a vector giving the variables to be used for highlighting.
If |
selection |
the selection method for highlighting missing/imputed
values in multiple highlight variables. Possible values are |
plotvars |
a vector giving the variables to be plotted. If |
col |
a vector of length three giving the colors to be used in the plot. The second/third color will be used for highlighting missing/imputed values. |
alpha |
a numeric value between 0 and 1 giving the level of
transparency of the colors, or |
pch |
a vector of length two giving the plot characters. The second plot character will be used for the highlighted observations. |
lty |
a vector of length two giving the line types for the density
plots in the diagonal panels (if |
diagonal |
a character string specifying the plot to be drawn in the
diagonal panels. Possible values are |
interactive |
a logical indicating whether the variables to be used for highlighting can be selected interactively (see ‘Details’). |
... |
for |
scattmatrixMiss uses pairsVIM() with a panel function
that allows highlighting of missing/imputed values.
If interactive=TRUE, the variables to be used for highlighting can be
selected interactively. Observations with missing/imputed values in any or
in all of the selected variables are highlighted (as determined by
selection). A variable can be added to the selection by clicking in
a diagonal panel. If a variable is already selected, clicking on the
corresponding diagonal panel removes it from the selection. Clicking
anywhere else quits the interactive session.
The graphical parameter oma will be set unless supplied as an
argument.
TKRscattmatrixMiss behaves like scattmatrixMiss, but uses
tkrplot to embed the plot in a Tcl/Tk window.
This is useful if the number of variables is large, because scrollbars allow
to move from one part of the plot to another.
Some of the argument names and positions have changed with version 1.3
due to a re-implementation and for more consistency with other plot
functions in VIM. For back compatibility, the argument
colcomb can still be supplied to ...{} and is handled
correctly. Nevertheless, it is deprecated and no longer documented. Use
highlight instead. The arguments smooth, reg.line and
legend.plot are no longer used and ignored if supplied.
Andreas Alfons, Matthias Templ, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
spineMiss()
data(sleep, package = "VIM") ## for missing values x <- sleep[, 1:5] x[,c(1,2,4)] <- log10(x[,c(1,2,4)]) scattmatrixMiss(x, highlight = "Dream") ## for imputed values x_imp <- kNN(sleep[, 1:5]) x_imp[,c(1,2,4)] <- log10(x_imp[,c(1,2,4)]) scattmatrixMiss(x_imp, delimiter = "_imp", highlight = "Dream")data(sleep, package = "VIM") ## for missing values x <- sleep[, 1:5] x[,c(1,2,4)] <- log10(x[,c(1,2,4)]) scattmatrixMiss(x, highlight = "Dream") ## for imputed values x_imp <- kNN(sleep[, 1:5]) x_imp[,c(1,2,4)] <- log10(x_imp[,c(1,2,4)]) scattmatrixMiss(x_imp, delimiter = "_imp", highlight = "Dream")
In addition to a standard scatterplot, lines are plotted for the missing values in one variable. If there are imputed values, they will be highlighted.
scattMiss( x, delimiter = NULL, side = 1, col = c("skyblue", "red", "orange", "lightgrey"), alpha = NULL, lty = c("dashed", "dotted"), lwd = par("lwd"), quantiles = c(0.5, 0.975), inEllipse = FALSE, zeros = FALSE, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, interactive = TRUE, ... )scattMiss( x, delimiter = NULL, side = 1, col = c("skyblue", "red", "orange", "lightgrey"), alpha = NULL, lty = c("dashed", "dotted"), lwd = par("lwd"), quantiles = c(0.5, 0.975), inEllipse = FALSE, zeros = FALSE, xlim = NULL, ylim = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, interactive = TRUE, ... )
x |
a |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
side |
if |
col |
a vector of length four giving the colors to be used in the plot. The first color is used for the scatterplot, the second/third color for the rug representation for missing/imputed values. The second color is also used for the lines for missing values. Imputed values will be highlighted with the third color, and the fourth color is used for the ellipses (see ‘Details’). If only one color is supplied, it is used for the scatterplot, the rug representation and the lines, whereas the default color is used for the ellipses. Else if a vector of length two is supplied, the default color is used for the ellipses as well. |
alpha |
a numeric value between 0 and 1 giving the level of
transparency of the colors, or |
lty |
a vector of length two giving the line types for the lines and ellipses. If a single value is supplied, it will be used for both. |
lwd |
a vector of length two giving the line widths for the lines and ellipses. If a single value is supplied, it will be used for both. |
quantiles |
a vector giving the quantiles of the chi-square
distribution to be used for the tolerance ellipses, or |
inEllipse |
plot lines only inside the largest ellipse. Ignored if
|
zeros |
a logical vector of length two indicating whether the variables
are semi-continuous, i.e., contain a considerable amount of zeros. If
|
xlim, ylim
|
axis limits. |
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
interactive |
a logical indicating whether the |
... |
further graphical parameters to be passed down (see
|
Information about missing values in one variable is included as vertical or
horizontal lines, as determined by the side argument. The lines are
thereby drawn at the observed x- or y-value. In case of imputed values, they
will additionally be highlighted in the scatterplot. Supplementary,
percentage coverage ellipses can be drawn to give a clue about the shape of
the bivariate data distribution.
If interactiveis TRUE, clicking in the bottom margin redraws
the plot with information about missing/imputed values in the first variable
and clicking in the left margin redraws the plot with information about
missing/imputed values in the second variable. Clicking anywhere else in
the plot quits the interactive session.
The argument zeros has been introduced in version 1.4. As a
result, some of the argument positions have changed.
Andreas Alfons, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattmatrixMiss(),
spineMiss()
data(tao, package = "VIM") ## for missing values scattMiss(tao[,c("Air.Temp", "Humidity")]) ## for imputed values scattMiss(kNN(tao[,c("Air.Temp", "Humidity")]), delimiter = "_imp")data(tao, package = "VIM") ## for missing values scattMiss(tao[,c("Air.Temp", "Humidity")]) ## for imputed values scattMiss(kNN(tao[,c("Air.Temp", "Humidity")]), delimiter = "_imp")
Sleep data with missing values.
A data frame with 62 observations on the following 10 variables.
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
Allison, T. and Chichetti, D. (1976) Sleep in mammals: ecological and constitutional correlates. Science 194 (4266), 732–734.
The data set was imported from GGobi.
data(sleep, package = "VIM") summary(sleep) aggr(sleep)data(sleep, package = "VIM") summary(sleep) aggr(sleep)
Spineplot or spinogram with highlighting of missing/imputed values in other variables by splitting each cell into two parts. Additionally, information about missing/imputed values in the variable of interest is shown on the right hand side.
spineMiss( x, delimiter = NULL, pos = 1, selection = c("any", "all"), breaks = "Sturges", right = TRUE, col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), border = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, labels = axes, only.miss = TRUE, miss.labels = axes, interactive = TRUE, ... )spineMiss( x, delimiter = NULL, pos = 1, selection = c("any", "all"), breaks = "Sturges", right = TRUE, col = c("skyblue", "red", "skyblue4", "red4", "orange", "orange4"), border = NULL, main = NULL, sub = NULL, xlab = NULL, ylab = NULL, axes = TRUE, labels = axes, only.miss = TRUE, miss.labels = axes, interactive = TRUE, ... )
x |
a vector, matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
pos |
a numeric value giving the index of the variable of interest.
Additional variables in |
selection |
the selection method for highlighting missing/imputed
values in multiple additional variables. Possible values are |
breaks |
if the variable of interest is numeric, |
right |
logical; if |
col |
a vector of length six giving the colors to be used. If only one color is supplied, the bars are transparent and the supplied color is used for highlighting missing/imputed values. Else if two colors are supplied, they are recycled. |
border |
the color to be used for the border of the cells. Use
|
main, sub
|
main and sub title. |
xlab, ylab
|
axis labels. |
axes |
a logical indicating whether axes should be drawn on the plot. |
labels |
if the variable of interest is categorical, either a logical indicating whether labels should be plotted below each cell, or a character vector giving the labels. This is ignored if the variable of interest is numeric. |
only.miss |
logical; if |
miss.labels |
either a logical indicating whether label(s) should be plotted below the cell(s) on the right hand side, or a character string or vector giving the label(s) (see ‘Details’). |
interactive |
a logical indicating whether the variables can be switched interactively (see ‘Details’). |
... |
further graphical parameters to be passed to
|
A spineplot is created if the variable of interest is categorial and a spinogram if it is numerical. The horizontal axis is scaled according to relative frequencies of the categories/classes. If more than one variable is supplied, the cells are split according to missingness/number of imputed values in the additional variables. Thus the proportion of highlighted observations in each category/class is displayed on the vertical axis. Since the height of each cell corresponds to the proportion of highlighted observations, it is now possible to compare the proportions of missing/imputed values among the different categories/classes.
If only.miss=TRUE, the missing/imputed values in the variable of
interest are also visualized by a cell in the spine plot or spinogram. If
additional variables are supplied, this cell is again split into two parts
according to missingness/number if imputed values in the additional
variables.
Otherwise, a small spineplot that visualizes missing/imputed values in the
variable of interest is drawn on the right hand side. The first cell
corresponds to observed values and the second cell to missing/imputed
values. Each of the two cells is again split into two parts according to
missingness/number of imputed values in the additional variables. Note that
this display does not make sense if only one variable is supplied, therefore
only.miss is ignored in that case.
If interactive=TRUE, clicking in the left margin of the plot results
in switching to the previous variable and clicking in the right margin
results in switching to the next variable. Clicking anywhere else on the
graphics device quits the interactive session.
a table containing the frequencies corresponding to the cells.
Some of the argument names and positions have changed with version 1.3
due to extended functionality and for more consistency with other plot
functions in VIM. For back compatibility, the arguments
xaxlabels and missaxlabels can still be supplied to
...{} and are handled correctly. Nevertheless, they are deprecated
and no longer documented. Use labels and miss.labels instead.
The code is based on the function graphics::spineplot() by Achim
Zeileis.
Andreas Alfons, Matthias Templ, modifications by Bernd Prantner
M. Templ, A. Alfons, P. Filzmoser (2012) Exploring incomplete data using visualization tools. Advances in Data Analysis and Classification, Online first. DOI: 10.1007/s11634-011-0102-y.
histMiss(), barMiss(),
mosaicMiss()
Other plotting functions:
aggr(),
barMiss(),
histMiss(),
marginmatrix(),
marginplot(),
matrixplot(),
mosaicMiss(),
pairsVIM(),
parcoordMiss(),
pbox(),
scattJitt(),
scattMiss(),
scattmatrixMiss()
data(tao, package = "VIM") data(sleep, package = "VIM") ## for missing values spineMiss(tao[, c("Air.Temp", "Humidity")]) spineMiss(sleep[, c("Exp", "Sleep")]) ## for imputed values spineMiss(kNN(tao[, c("Air.Temp", "Humidity")]), delimiter = "_imp") spineMiss(kNN(sleep[, c("Exp", "Sleep")]), delimiter = "_imp")data(tao, package = "VIM") data(sleep, package = "VIM") ## for missing values spineMiss(tao[, c("Air.Temp", "Humidity")]) spineMiss(sleep[, c("Exp", "Sleep")]) ## for imputed values spineMiss(kNN(tao[, c("Air.Temp", "Humidity")]), delimiter = "_imp") spineMiss(kNN(sleep[, c("Exp", "Sleep")]), delimiter = "_imp")
Create a reactable table that highlights missing values and imputed values
with the same colors as histMiss()
tableMiss(x, delimiter = "_imp")tableMiss(x, delimiter = "_imp")
x |
a vector, matrix or |
delimiter |
a character-vector to distinguish between variables and
imputation-indices for imputed variables (therefore, |
data(tao) x_IMPUTED <- kNN(tao[, c("Air.Temp", "Humidity")]) tableMiss(x_IMPUTED[105:114, ]) x_IMPUTED[106, 2] <- NA x_IMPUTED[105, 1] <- NA x_IMPUTED[107, "Humidity_imp"] <- TRUE tableMiss(x_IMPUTED[105:114, ])data(tao) x_IMPUTED <- kNN(tao[, c("Air.Temp", "Humidity")]) tableMiss(x_IMPUTED[105:114, ]) x_IMPUTED[106, 2] <- NA x_IMPUTED[105, 1] <- NA x_IMPUTED[107, "Humidity_imp"] <- TRUE tableMiss(x_IMPUTED[105:114, ])
A small subsample of the Tropical Atmosphere Ocean (TAO) project data,
derived from the GGOBI project.
A data frame with 736 observations on the following 8 variables.
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
a numeric vector
zonal wind, i.e. latitude-parallel wind
meridional wind, i.e. longitude-parallel wind
All cases recorded for five locations and two time periods.
data(tao, package = "VIM") summary(tao) aggr(tao)data(tao, package = "VIM") summary(tao) aggr(tao)
2 numeric, 2 binary, 2 nominal and 2 mixed (semi-continous) variables
The format is: List of 4
$wna : a data.frame with 500 obs. of 8 variables:
x1: numeric 10.87 9.53 7.83 8.53 8.67 ...
x2: numeric 10.9 9.32 7.68 8.2 8.41 ... ..
c1: Factor w/ 4 levels "a","b","c","d": 3 2 2 1 2 2 1 3 3 2 ...
c2: Factor w/ 4 levels "a","b","c","d": 2 3 2 2 2 2 2 4 2 2 ...
b1: Factor w/ 2 levels "0","1": 2 2 1 2 1 2 1 2 1 1 ...
b2: Factor w/ 2 levels "0","1": 2 2 1 1 1 1 1 2 2 2 ...
m1: numeric 0 8.29 9.08 0 0 ...
m2: numeric 10.66 9.39 7.8 8.11 7.33 ...
$wona : a 'data.frame“ with 500 obs. of 8 variables:
x1: numeric 10.87 9.53 7.83 8.53 8.67 ...
x2: numeric 10.9 9.32 7.68 8.2 8.41 ...
c1: Factor w/ 4 levels "a","b","c","d": 3 2 2 1 2 2 1 3 3 2 ...
c2: Factor w/ 4 levels "a","b","c","d": 2 3 2 2 2 2 2 4 2 2 ...
b1: Factor w/ 2 levels "0","1": 2 2 1 2 1 2 1 2 1 1 ...
b2: Factor w/ 2 levels "0","1": 2 2 1 1 1 1 1 2 2 2 ...
m1: numeric 0 8.29 9.08 0 0 ...
m2: numeric 10.66 9.39 7.8 8.11 7.33 ...
$mixed: c("m1", "m2")
$outlierInd: 'NULL“
data(testdata)data(testdata)
A 2-dimensional data set with additional information.
data frame with 100 observations and 12 variables. The first two variables represent the fully observed data.
data(toydataMiss)data(toydataMiss)
vimpute() methodRemove a user-registered vimpute() method
unregister_vimpute_method(name)unregister_vimpute_method(name)
name |
Single character string: the method name to remove. Built-in methods cannot be removed. |
Invisibly TRUE on success.
register_vimpute_method(), vimpute_methods()
Other vimpute method registry:
register_vimpute_method(),
vimpute_methods()
register_vimpute_method("cart", learner = list(regr = "regr.rpart", classif = "classif.rpart")) unregister_vimpute_method("cart")register_vimpute_method("cart", learner = list(regr = "regr.rpart", classif = "classif.rpart")) unregister_vimpute_method("cart")
Converts a vimmi object to long format and uses
mice::as.mids() to create a proper mids object.
This enables use of mice::pool(), mice::with.mids(),
and other mice infrastructure.
vim_as_mids(x, ...) as.mids.vimmi(x, ...)vim_as_mids(x, ...) as.mids.vimmi(x, ...)
x |
A |
... |
Currently unused |
vim_as_mids() is the documented name. as.mids.vimmi() is the
same function under its historical name (kept for backward compatibility):
despite the dotted suffix it is a plain function, not an S3 method –
mice::as.mids() is not a generic, so it never dispatches on
vimmi objects.
A mids object (from the mice package)
## Not run: result <- vimpute(sleep, method = "ranger", m = 5, boot = TRUE, uncert = "normalerror") mids_obj <- vim_as_mids(result) # Now use mice infrastructure: # fits <- with(mids_obj, lm(Sleep ~ Dream + Span)) # mice::pool(fits) ## End(Not run)## Not run: result <- vimpute(sleep, method = "ranger", m = 5, boot = TRUE, uncert = "normalerror") mids_obj <- vim_as_mids(result) # Now use mice infrastructure: # fits <- with(mids_obj, lm(Sleep ~ Dream + Span)) # mice::pool(fits) ## End(Not run)
Reconstructs one or more completed datasets by filling in imputed values from the specified imputation(s).
vim_complete(data, action = 1, ...) ## S3 method for class 'vimmi' complete(data, action = 1, ...)vim_complete(data, action = 1, ...) ## S3 method for class 'vimmi' complete(data, action = 1, ...)
data |
A |
action |
Specifies which completed dataset(s) to return:
|
... |
Currently unused |
vim_complete() is the documented name and always works. The same
function is additionally registered as an S3 method on
mice::complete() and tidyr::complete(), so if either package
is attached the familiar complete(result, 1) dispatches to it.
VIM deliberately does not export a complete() generic of its
own. Both mice and tidyr export a generic of that name, so an
exported VIM generic would mask them (and be masked by them), and would make
any package that imports VIM and one of those packages wholesale emit
“replacing previous import” at load time. Registering the method on
the foreign generics gives the same user-facing call without the clash –
the same approach VIM takes for vim_as_mids.
A data.frame, list of data.frames, or long-format data.frame
## Not run: result <- vimpute(sleep, method = "ranger", m = 5, boot = TRUE, uncert = "normalerror") d1 <- vim_complete(result, 1) # first completed dataset all_d <- vim_complete(result, "all") # list of 5 datasets long_d <- vim_complete(result, "long") # long format with .imp column # With mice or tidyr attached, the generic dispatches to the same function: # library(mice); d1 <- complete(result, 1) ## End(Not run)## Not run: result <- vimpute(sleep, method = "ranger", m = 5, boot = TRUE, uncert = "normalerror") d1 <- vim_complete(result, 1) # first completed dataset all_d <- vim_complete(result, "all") # list of 5 datasets long_d <- vim_complete(result, "long") # long format with .imp column # With mice or tidyr attached, the generic dispatches to the same function: # library(mice); d1 <- complete(result, 1) ## End(Not run)
S3 class for storing multiple imputations from vimpute.
Stores the original data once and only the imputed values per variable per
imputation, for memory efficiency.
## S3 method for class 'vimmi' print(x, ...) ## S3 method for class 'vimmi' summary(object, ...)## S3 method for class 'vimmi' print(x, ...) ## S3 method for class 'vimmi' summary(object, ...)
x |
A |
... |
Currently unused |
object |
A |
A vimmi object is returned by vimpute when m > 1.
It contains:
dataThe original data.frame with NAs intact (stored once).
impNamed list: for each variable with missings, a data.frame
with nmis rows and m columns of imputed values.
whereLogical matrix indicating which cells were imputed.
mInteger: number of imputations.
nmisNamed integer vector of missing counts per variable.
methodNamed list of imputation methods used per variable.
bootLogical: was bootstrap resampling used?
uncertCharacter: uncertainty method used.
callThe original function call.
tuning_logTuning report of the (single) tuning run, or NULL.
chainPer-iteration chain statistics (mean/var
arrays [variable, iteration, imputation]) behind
plot.vimmi trace plots.
seedThe seed applied at entry, or NULL.
Use vim_complete to extract completed datasets,
with.vimmi to fit models across imputations (returns a
mice-compatible mira), vim_as_mids to convert to a
mice mids object for pooling with mice::pool(), and
plot.vimmi for convergence trace plots.
Matthias Templ
vimpute, vim_complete,
with.vimmi, vim_as_mids,
plot.vimmi
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimpute(),
xgboostImpute()
## Not run: # Multiple imputation with bootstrap and normal error uncertainty result <- vimpute(sleep, method = "ranger", m = 5, boot = TRUE, uncert = "normalerror") print(result) summary(result) # Extract completed datasets d1 <- vim_complete(result, 1) all_d <- vim_complete(result, "all") # complete(result, 1) does the same when mice or tidyr is attached # Fit models and pool fits <- with(result, lm(Sleep ~ Dream + Span)) # mice::pool(fits) # requires mice ## End(Not run)## Not run: # Multiple imputation with bootstrap and normal error uncertainty result <- vimpute(sleep, method = "ranger", m = 5, boot = TRUE, uncert = "normalerror") print(result) summary(result) # Extract completed datasets d1 <- vim_complete(result, 1) all_d <- vim_complete(result, "all") # complete(result, 1) does the same when mice or tidyr is attached # Fit models and pool fits <- with(result, lm(Sleep ~ Dream + Span)) # mice::pool(fits) # requires mice ## End(Not run)
Impute missing values with prefered model, sequentially, with hyperparametertuning and with PMM (if wanted)
vimpute( data, ..., considered_variables = names(data), method = setNames(as.list(rep("ranger", length(considered_variables))), considered_variables), pmm = FALSE, pmm_k = NULL, pmm_k_method = "mean", learner_params = NULL, formula = FALSE, makeNA = NULL, donorcond = NULL, sequential = TRUE, nseq = 10, eps = 0.005, imp_var = TRUE, keep_all_columns = TRUE, pred_history = FALSE, tune = FALSE, verbose = FALSE, boot = NULL, robustboot = "stratified", uncert = "pmm", m = 1L, seed = NULL, tuned_params = NULL, tune_control = NULL, predictors = NULL, visit_sequence = "asis", spec = NULL )vimpute( data, ..., considered_variables = names(data), method = setNames(as.list(rep("ranger", length(considered_variables))), considered_variables), pmm = FALSE, pmm_k = NULL, pmm_k_method = "mean", learner_params = NULL, formula = FALSE, makeNA = NULL, donorcond = NULL, sequential = TRUE, nseq = 10, eps = 0.005, imp_var = TRUE, keep_all_columns = TRUE, pred_history = FALSE, tune = FALSE, verbose = FALSE, boot = NULL, robustboot = "stratified", uncert = "pmm", m = 1L, seed = NULL, tuned_params = NULL, tune_control = NULL, predictors = NULL, visit_sequence = "asis", spec = NULL )
data |
Dataset with missing values. Provide as a data.table. |
... |
Optional bare grammar formulas, one per variable:
|
considered_variables |
A character vector of variable names to be either imputed or used as predictors, excluding irrelevant columns from the imputation process. Excluded columns are still returned unchanged by default (see |
method |
Specifies the imputation method for each variable. Can be provided either:
|
pmm |
Predictive Mean Matching (PMM) settings. Can be provided:
|
pmm_k |
Number of nearest neighbors used in PMM. Accepted forms:
|
pmm_k_method |
Aggregation method used when
|
learner_params |
Hyperparameters for the chosen methods. Can be provided in three ways:
|
formula |
Optional modeling formula to restrict or transform predictor variables. Only supported for methods whose registry entry declares formula support: among the built-ins regularized (glmnet), robust (lmrob/glmrob), gam (mgcv::gam), robgam (robust GAM), and restricted (ECOSolveR least-squares with validate rules) Provide as a named list, e.g.:
|
makeNA |
Optional named list that defines additional values to be treated as imputable missing
values per variable, similar to |
donorcond |
Optional named list of donor conditions per variable, similar to |
sequential |
If TRUE, all variables with missing data are imputed sequentially across iterations. |
nseq |
Maximum number of iterations (if sequential is TRUE). |
eps |
Convergence threshold on the per-variable relative change between
iterations: for numeric variables the mean squared change of the imputed
values divided by the variance of the observed values, for factors the
share of imputed cells whose category changed. The sequential process
stops early once the largest per-variable change stays below |
imp_var |
If TRUE, additional columns indicating imputed values (VAR_imp) are added. |
keep_all_columns |
If TRUE (default), the full input is returned: columns excluded via
|
pred_history |
If TRUE, all predicted values across all iterations are stored. |
tune |
Hyperparameter tuning flag. Can be:
|
verbose |
If TRUE additional debugging output is provided |
boot |
If TRUE, bootstrap resampling is applied before model fitting to account
for model uncertainty. Defaults to |
robustboot |
Bootstrap strategy when |
uncert |
Imputation uncertainty method applied to numeric predictions:
|
m |
Number of multiple imputations. Default: 1 (single imputation).
When |
seed |
Optional single number for reproducibility. Applied once via
|
tuned_params |
Optional named list mapping variable names to learner parameter lists
(e.g. |
tune_control |
|
predictors |
Optional per-variable predictor control, the equivalent of mice's
|
visit_sequence |
Order in which the variables with missings are imputed:
|
spec |
|
Missingness assumptions. Like all conditional (fully
conditional specification) imputation, vimpute() assumes the data
are MAR (missing at random: the probability of missingness may
depend on observed values) – which includes MCAR
(missing completely at random) as a special case. Under MNAR
(missingness depending on the unobserved values themselves) imputations
and downstream estimates can be biased, and no imputation method can fix
this from the observed data alone; sensitivity analyses are advisable.
makeMissing generates MCAR/MAR/MNAR missingness in complete
data for exactly such simulation-based checks, and
overimpute diagnoses the calibration of the imputation
model on the observed cells.
For m = 1: the imputed dataset, classed like the input
(data.frame in, data.frame out; data.table in, data.table out). When
tune = TRUE the tuning report is attached as
attr(result, "tuning_log"); when pred_history = TRUE the
prediction history is attached as attr(result, "pred_history");
sequential runs attach the per-variable convergence matrix as
attr(result, "convergence") and the chain statistics as
attr(result, "chain"); the per-variable model quality (NRMSE/PFC,
out-of-bag for ranger, in-sample otherwise) is attached as
attr(result, "model_error") – the return is always the data
itself, never a wrapper list.
For m > 1: a vimmi object.
Eileen Vattheuer, Matthias Templ, Alexander Kowarik
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
xgboostImpute()
## Not run: # Single imputation (default) x <- vimpute(data = sleep, sequential = FALSE) # Sequential imputation with 3 iterations y <- vimpute(data = sleep, sequential = TRUE, nseq = 3) # Impute only selected variables z <- vimpute(data = sleep, considered_variables = c("Sleep", "Dream", "Span", "BodyWgt"), sequential = FALSE) # Multiple imputation (m = 5) with bootstrap and residual uncertainty # Returns a vimmi object result <- vimpute(data = sleep, method = "ranger", sequential = FALSE, imp_var = FALSE, m = 5, boot = TRUE, uncert = "resid") print(result) # Extract completed datasets d1 <- vim_complete(result, 1) # first imputed dataset all_d <- vim_complete(result, "all") # list of 5 datasets long_d <- vim_complete(result, "long") # long format with .imp column # Fit a model on each imputed dataset fits <- with(result, lm(Sleep ~ Dream + Span)) # Multiple imputation with robust method and residual uncertainty result2 <- vimpute(data = sleep, method = "robust", m = 5, boot = TRUE, robustboot = "stratified", uncert = "normalerror") ## End(Not run)## Not run: # Single imputation (default) x <- vimpute(data = sleep, sequential = FALSE) # Sequential imputation with 3 iterations y <- vimpute(data = sleep, sequential = TRUE, nseq = 3) # Impute only selected variables z <- vimpute(data = sleep, considered_variables = c("Sleep", "Dream", "Span", "BodyWgt"), sequential = FALSE) # Multiple imputation (m = 5) with bootstrap and residual uncertainty # Returns a vimmi object result <- vimpute(data = sleep, method = "ranger", sequential = FALSE, imp_var = FALSE, m = 5, boot = TRUE, uncert = "resid") print(result) # Extract completed datasets d1 <- vim_complete(result, 1) # first imputed dataset all_d <- vim_complete(result, "all") # list of 5 datasets long_d <- vim_complete(result, "long") # long format with .imp column # Fit a model on each imputed dataset fits <- with(result, lm(Sleep ~ Dream + Span)) # Multiple imputation with robust method and residual uncertainty result2 <- vimpute(data = sleep, method = "robust", m = 5, boot = TRUE, robustboot = "stratified", uncert = "normalerror") ## End(Not run)
vimpute()
List the imputation methods registered for vimpute()
vimpute_methods()vimpute_methods()
Character vector of registered method names (built-ins plus any
methods added via register_vimpute_method()).
register_vimpute_method(), unregister_vimpute_method()
Other vimpute method registry:
register_vimpute_method(),
unregister_vimpute_method()
vimpute_methods()vimpute_methods()
Returns the search space and default evaluation budget that
vimpute(tune = TRUE) uses for one of its built-in learners. The bounds
and budgets scale with the task size. Useful as the starting point for a
search_space hook in register_vimpute_method() and for inspecting
what the tuner explores.
vimpute_search_space(learner_id, task)vimpute_search_space(learner_id, task)
learner_id |
Single string: an mlr3 learner id used by vimpute's
built-in methods, e.g. |
task |
An mlr3 task (its number of rows scales the bounds and the budget). |
A list with elements space (a paradox::ParamSet, or NULL
if the learner has no built-in space) and n_evals (the default
evaluation budget).
vimpute_tune_control(), register_vimpute_method()
## Not run: task <- mlr3::TaskRegr$new("t", backend = data.frame(y = 1:20, x = 1:20), target = "y") vimpute_search_space("regr.ranger", task) ## End(Not run)## Not run: task <- mlr3::TaskRegr$new("t", backend = data.frame(y = 1:20, x = 1:20), target = "y") vimpute_search_space("regr.ranger", task) ## End(Not run)
vimpute()
Bundles everything vimpute() can configure for a single variable –
method, learner parameters, formula or predictors, tune, PMM
settings, makeNA values and a donorcond donor condition – into one
object, instead of coordinating up to nine parallel per-variable
arguments. Pass a named list of specs as vimpute(spec = ); the reserved
name ".default" supplies the spec for variables not listed (its method,
learner parameters and tune/PMM knobs; formula/predictors/makeNA/
donorcond are variable-specific and not allowed in ".default").
vimpute_spec( method, ..., formula = NULL, predictors = NULL, tune = FALSE, pmm = FALSE, pmm_k = NULL, pmm_k_method = NULL, makeNA = NULL, donorcond = NULL, uncert = NULL ) vs_ranger(...) vs_xgboost(...) vs_regularized(...) vs_robust(...) vs_gam(...) vs_robgam(...) ## S3 method for class 'vimpute_spec' print(x, ...)vimpute_spec( method, ..., formula = NULL, predictors = NULL, tune = FALSE, pmm = FALSE, pmm_k = NULL, pmm_k_method = NULL, makeNA = NULL, donorcond = NULL, uncert = NULL ) vs_ranger(...) vs_xgboost(...) vs_regularized(...) vs_robust(...) vs_gam(...) vs_robgam(...) ## S3 method for class 'vimpute_spec' print(x, ...)
method |
Single string: a registered imputation method (see
|
... |
Named learner parameters for the method's learners (e.g.
|
formula |
One-sided ( |
predictors |
Character vector of predictor columns (the
|
tune |
Logical: tune this variable's learner (see
|
pmm |
Logical: predictive mean matching for this (numeric) variable. |
pmm_k |
|
pmm_k_method |
|
makeNA |
|
donorcond |
|
uncert |
Not a spec knob – set |
x |
A |
Learner parameters in ... are validated eagerly against the
method's learner parameter sets, so a typo fails at the constructor call,
not in iteration 7 of the imputation. vs_ranger(), vs_xgboost(),
vs_regularized(), vs_robust(), vs_gam() and vs_robgam() are
shorthands for the built-in methods; methods added via
register_vimpute_method() use vimpute_spec("<name>", ...).
A variable with a spec uses that spec's settings exactly (no field-level
merging with ".default"). uncert remains a call-level argument of
vimpute() and is not a spec knob.
An object of class vimpute_spec.
vimpute(), register_vimpute_method()
## Not run: data(sleep) res <- vimpute(sleep, spec = list( Sleep = vs_ranger(num.trees = 300, tune = TRUE), NonD = vs_robust(donorcond = ">= 0"), .default = vs_ranger() ), seed = 1) # the same, as formula grammar: res2 <- vimpute(sleep, Sleep ~ . | ranger(num.trees = 300, tune = TRUE), NonD ~ . | robust(donorcond = ">= 0"), .default = vs_ranger(), seed = 1) ## End(Not run)## Not run: data(sleep) res <- vimpute(sleep, spec = list( Sleep = vs_ranger(num.trees = 300, tune = TRUE), NonD = vs_robust(donorcond = ">= 0"), .default = vs_ranger() ), seed = 1) # the same, as formula grammar: res2 <- vimpute(sleep, Sleep ~ . | ranger(num.trees = 300, tune = TRUE), NonD ~ . | robust(donorcond = ">= 0"), .default = vs_ranger(), seed = 1) ## End(Not run)
vimpute()
Bundles the tuning controls that vimpute(tune = TRUE) previously
hard-coded: the evaluation budget, the cross-validation folds of the
tuning resampling, the mlr3tuning tuner and its batch size. Pass the
result to vimpute(tune_control = ). With m > 1 the control applies to
the single tuning run (run 1), whose parameters all m imputations share.
vimpute_tune_control( budget = NULL, folds = NULL, tuner = "random_search", batch_size = 1L )vimpute_tune_control( budget = NULL, folds = NULL, tuner = "random_search", batch_size = 1L )
budget |
|
folds |
|
tuner |
Single string: an mlr3tuning tuner id, e.g.
|
batch_size |
Single positive integer: configurations evaluated per
tuner batch. The default |
Nested resampling is intentionally not offered: the goal of tuning inside
an imputation loop is good imputations, not an unbiased estimate of the
learner's generalisation error, and the tuned-vs-default comparison that
vimpute() runs on a fresh resampling already guards against tuning that
overfits the folds.
An object of class vimpute_tune_control.
vimpute(), vimpute_search_space()
## Not run: data(sleep) res <- vimpute(sleep[, c("Sleep", "Dream", "Span")], method = "ranger", tune = TRUE, sequential = FALSE, tune_control = vimpute_tune_control(budget = 10, folds = 3)) attr(res, "tuning_log") ## End(Not run)## Not run: data(sleep) res <- vimpute(sleep[, c("Sleep", "Dream", "Span")], method = "ranger", tune = TRUE, sequential = FALSE, tune_control = vimpute_tune_control(budget = 10, folds = 3)) attr(res, "tuning_log") ## End(Not run)
Wine reviews from France, Switzerland, Austria and Germany.
A data frame with 9627 observations on the following 9 variables.
country of origin
the number of points WineEnthusiast rated the wine on a scale of 1-100 (though they say they only post reviews for wines that score >=80)
the cost for a bottle of the wine
the province or state that the wine is from
name of the person who tasted and reviewed the wine
Twitter handle for the person who tasted ane reviewed the wine
the type of grapes used to make the wine (ie pinot noir)
the winery that made the wine
broader category as variety
The data was scraped from WineEnthusiast during the week of Nov 22th, 2017. The code for the scraper can be found at https://github.com/zackthoutt/wine-deep-learning This data set is slightly modified, i.e. only four countries are selected and broader categories on the variety have been added.
https://www.kaggle.com/zynicide/wine-reviews
data(wine) str(wine) aggr(wine)data(wine) str(wine) aggr(wine)
Applies an expression (typically a model fit) to each completed dataset
in a vimmi object. The return is a mice-compatible mira
object (elements call, call1, nmis, analyses),
so the standard mice pipeline runs unchanged: mice::pool(),
summary(mice::pool(fits)), mice::getfit(fits). The mice
package is not needed to create the object, only to pool it; for
mitools::MIcombine() pass the fit list fits$analyses.
## S3 method for class 'vimmi' with(data, expr, ...)## S3 method for class 'vimmi' with(data, expr, ...)
data |
A |
expr |
An expression to evaluate, e.g. |
... |
Currently unused |
An object of class mira: the m results are in
$analyses (extract with mice::getfit())
## Not run: result <- vimpute(sleep, method = "ranger", m = 5, boot = TRUE, uncert = "normalerror") fits <- with(result, lm(Sleep ~ Dream + Span)) # Pool with mice: # mice::pool(fits) ## End(Not run)## Not run: result <- vimpute(sleep, method = "ranger", m = 5, boot = TRUE, uncert = "normalerror") fits <- with(result, lm(Sleep ~ Dream + Span)) # Pool with mice: # mice::pool(fits) ## End(Not run)
Impute missing values based on a random forest model using xgboost::xgboost()
xgboostImpute( formula, data, imp_var = TRUE, imp_suffix = "imp", verbose = FALSE, nrounds = 100, objective = NULL, ... )xgboostImpute( formula, data, imp_var = TRUE, imp_suffix = "imp", verbose = FALSE, nrounds = 100, objective = NULL, ... )
formula |
model formula for the imputation |
data |
A |
imp_var |
|
imp_suffix |
suffix used for TF imputation variables |
verbose |
Show the number of observations used for training
and evaluating the RF-Model. This parameter is also passed down to
|
nrounds |
max number of boosting iterations,
argument passed to |
objective |
objective for xgboost,
argument passed to |
... |
Arguments passed to |
the imputed data set.
Other imputation methods:
hotdeck(),
impPCA(),
imputeCellEM(),
imputeCellIRMI(),
imputeCellM(),
imputeCellMCD(),
imputeCellwise(),
imputeRobust(),
imputeRobustChain(),
irmi(),
kNN(),
matchImpute(),
medianSamp(),
rangerImpute(),
regressionImp(),
sampleCat(),
vimmi,
vimpute()
data(sleep) sleepx <- sleep sleepx$Pred <- as.factor(LETTERS[sleepx$Pred]) sleepx$Pred[1] <- NA # a numeric and a factor target imputed at once; nrounds = 30 keeps the # example fast (the default is 100 boosting rounds) # xgboostImpute() runs on vimpute(), which VIM backs with the suggested # mlr3 stack -- skip the example where that stack is not installed. if (requireNamespace("mlr3", quietly = TRUE) && requireNamespace("mlr3learners", quietly = TRUE) && requireNamespace("mlr3pipelines", quietly = TRUE)) { imp <- xgboostImpute(Dream + Pred ~ BodyWgt + BrainWgt, data = sleepx, nrounds = 30) head(imp) }data(sleep) sleepx <- sleep sleepx$Pred <- as.factor(LETTERS[sleepx$Pred]) sleepx$Pred[1] <- NA # a numeric and a factor target imputed at once; nrounds = 30 keeps the # example fast (the default is 100 boosting rounds) # xgboostImpute() runs on vimpute(), which VIM backs with the suggested # mlr3 stack -- skip the example where that stack is not installed. if (requireNamespace("mlr3", quietly = TRUE) && requireNamespace("mlr3learners", quietly = TRUE) && requireNamespace("mlr3pipelines", quietly = TRUE)) { imp <- xgboostImpute(Dream + Pred ~ BodyWgt + BrainWgt, data = sleepx, nrounds = 30) head(imp) }