Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
missRanger
https://mayer79.github.io/missRanger/
Admin
missRanger is a multivariate imputation algorithm based on random forests.
Tokens:
14,554
Snippets:
139
Trust Score:
9.7
Update:
4 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install missRanger Package Source: https://mayer79.github.io/missRanger/index.html Install the missRanger package from CRAN or the development version from GitHub. ```r install.packages("missRanger") # Development version devtools::install_github("mayer79/missRanger") ``` -------------------------------- ### Install missRanger Development Version Source: https://mayer79.github.io/missRanger/articles/missRanger.html Install the latest development version of the missRanger package from GitHub. ```r devtools::install_github("mayer79/missRanger") ``` -------------------------------- ### Interactive Program Notice (GNU GPL) Source: https://mayer79.github.io/missRanger/LICENSE.html A short notice to display when an interactive program starts, indicating its license terms and warranty status. ```text Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Example Data Output Source: https://mayer79.github.io/missRanger/articles/missRanger.html This snippet shows a typical data output format from missRanger, including numerical values and species classification. ```text ## Usage #> 5 5.061255 3.6 1.4 0.2000000 setosa #> 6 5.400000 3.9 1.7 0.4000000 setosa ``` ``` -------------------------------- ### Example Usage of pmm Function Source: https://mayer79.github.io/missRanger/reference/pmm.html Demonstrates how to use the pmm function with sample data to impute values. The example shows imputing values for xtest based on xtrain and ytrain, specifying k=1. ```R pmm(xtrain = c(0.2, 0.3, 0.8), xtest = c(0.7, 0.2), ytrain = 1:3, k = 1) # c(3, 1) #> [1] 3 1 ``` -------------------------------- ### Install missRanger from CRAN Source: https://mayer79.github.io/missRanger/articles/missRanger.html Install the stable version of the missRanger package from CRAN. ```r install.packages("missRanger") ``` -------------------------------- ### Formula Interface Examples for missRanger Source: https://mayer79.github.io/missRanger/news/index.html Illustrates various formula syntaxes for specifying imputation and predictor variables in missRanger. The default '. ~ .' uses all variables, while others allow for exclusion or specific variable selection. ```R missRanger(data, . ~ .) ``` ```R missRanger(data, . ~ . - ID) ``` ```R missRanger(data, Species ~ Sepal.Width) ``` ```R missRanger(data, Species + Sepal.Length ~ Species + Petal.Length) ``` ```R missRanger(data, . ~ 1) ``` -------------------------------- ### Impute Missing Values with missRanger Source: https://mayer79.github.io/missRanger/reference/predict.missRanger.html Demonstrates how to impute missing values in a dataset using the missRanger function. This example shows setting PMM parameters, number of trees, and enabling forest retention for subsequent predictions. It also includes progress indicators for the imputation iterations. ```r iris2 <- generateNA(iris, seed = 20, p = c(Sepal.Length = 0.2, Species = 0.1)) imp <- missRanger(iris2, pmm.k = 5, num.trees = 100, keep_forests = TRUE, seed = 2) #> Missing value imputation by random forests #> #> Variables to impute: Species, Sepal.Length #> Variables used to impute: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species #> #> iter 1 #> | | | 0% | |=================================== | 50% | |======================================================================| 100% #> #> iter 2 #> | | | 0% | |=================================== | 50% | |======================================================================| 100% #> #> iter 3 #> | | | 0% | |=================================== | 50% | |======================================================================| 100% #> #> iter 4 #> | | | 0% | |=================================== | 50% | |======================================================================| 100% ``` -------------------------------- ### Impute Missing Values with Random Forests Source: https://mayer79.github.io/missRanger/reference/missRanger.html Performs missing value imputation using random forests. This example demonstrates imputation on the iris dataset with specified parameters for k-nearest neighbors, number of trees, and data output format. The `seed` ensures reproducibility. ```R imp2 <- missRanger(iris2, pmm.k = 5, num.trees = 50, data_only = FALSE, seed = 1) ``` -------------------------------- ### Impute Missing Values in a Data Frame Source: https://mayer79.github.io/missRanger/reference/imputeUnivariate.html Shows how to impute missing values in a data frame using imputeUnivariate. This example applies imputation to the iris dataset after introducing missing values with generateNA. ```R head(imputeUnivariate(generateNA(iris))) ``` -------------------------------- ### Controlling Random Forest Parameters Source: https://mayer79.github.io/missRanger/articles/missRanger.html Impute missing values while controlling random forest parameters like number of trees and mtry. This example uses 200 trees and one feature per split. ```r imp <- missRanger(iris_NA, pmm.k = 5, num.trees = 200, mtry = 1, verbose = 0) ``` -------------------------------- ### Predict Missing Values with missRanger Source: https://mayer79.github.io/missRanger/reference/predict.missRanger.html Applies the trained missRanger model to impute missing values in a subset of the original data. This example uses a fixed seed for reproducibility of the imputation process on the new data. ```r predict(imp, head(iris2), seed = 3) #> Sepal.Length Sepal.Width Petal.Length Petal.Width Species #> 1 5.1 3.5 1.4 0.2 setosa #> 2 4.4 3.0 1.4 0.2 setosa #> 3 4.7 3.2 1.3 0.2 setosa #> 4 4.6 3.1 1.5 0.2 setosa #> 5 5.1 3.6 1.4 0.2 setosa #> 6 6.0 3.9 1.7 0.4 setosa ``` -------------------------------- ### Add NA to a Data Frame Source: https://mayer79.github.io/missRanger/reference/generateNA.html Adds NA values to a data frame. The proportion of NAs can be specified globally or per column. This example shows adding NAs to the iris dataset. ```R head(generateNA(iris, p = 0.2)) ``` -------------------------------- ### Standard GNU GPL License Text Source: https://mayer79.github.io/missRanger/LICENSE.html This is the standard text to include at the beginning of each source file to apply the GPL and disclaim warranty. ```text <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ``` -------------------------------- ### Multiple Imputation Workflow with missRanger and mice Source: https://mayer79.github.io/missRanger/articles/multiple_imputation.html This snippet demonstrates the complete workflow for multiple imputation. It involves generating missing data, creating multiple imputed datasets using missRanger, running a linear model on each imputed dataset, and finally pooling the results using the mice package. It also shows how to compare these results with a model run on the original data. ```R library(missRanger) library(mice) set.seed(19) iris_NA <- generateNA(iris, p = c(0, 0.1, 0.1, 0.1, 0.1)) # Generate 20 complete data sets with relatively large pmm.k filled <- replicate( 20, missRanger(iris_NA, verbose = 0, num.trees = 100, pmm.k = 10), simplify = FALSE ) # Run a linear model for each of the completed data sets models <- lapply(filled, function(x) lm(Sepal.Length ~ ., x)) # Pool the results by mice summary(pooled_fit <- pool(models)) ``` ```R # Compare with model on original data summary(lm(Sepal.Length ~ ., data = iris)) ``` -------------------------------- ### Using mtry in missRanger Source: https://mayer79.github.io/missRanger/news/index.html Demonstrates how to specify the 'mtry' argument for controlling the number of variables randomly sampled as candidates at each split. Recommended values include NULL, 1, or a function of the number of covariates. ```R missRanger(data, mtry = function(m) max(1, m %/% 3)) ``` -------------------------------- ### Displaying Data Head Source: https://mayer79.github.io/missRanger/reference/missRanger.html Shows the first few rows of a dataset named 'imp1'. This is useful for quickly inspecting the structure and content of your data after an operation. ```r head(imp1) ``` -------------------------------- ### Saving and Loading Imputation Models Source: https://mayer79.github.io/missRanger/news/index.html Shows how to save and load a trained missRanger imputation model using base R functions. This allows for persistence and reuse of imputation models. ```R saveRDS(imp, "missRanger_model.rds") readRDS("missRanger_model.rds") ``` -------------------------------- ### summary(_<missRanger>_) Source: https://mayer79.github.io/missRanger/reference/index.html Summary Method for missRanger objects. ```APIDOC ## summary(_<missRanger>_) ### Description Summary Method for missRanger objects. ### Method Not applicable (function signature) ### Endpoint Not applicable (function signature) ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### Out-of-sample Imputation with missRanger Source: https://mayer79.github.io/missRanger/news/index.html Demonstrates how to perform out-of-sample imputation by keeping random forests and then applying them to new data. This is useful for applying trained imputation models to unseen datasets. ```R imp <- missRanger(..., keep_forests = TRUE) predict(imp, newdata) ``` -------------------------------- ### Print missRanger Object Source: https://mayer79.github.io/missRanger/reference/print.missRanger.html Demonstrates how to use the print method for a missRanger object. This shows the summary of the imputation process, including the variables imputed, the imputation error, and the best iteration. The imputed data can be extracted using the $data accessor. ```R CO2_ <- generateNA(CO2, seed = 1) imp <- missRanger(CO2_, pmm.k = 5, data_only = FALSE, num.threads = 1) #> Missing value imputation by random forests #> #> Variables to impute: Plant, Type, Treatment, conc, uptake #> Variables used to impute: Plant, Type, Treatment, conc, uptake #> #> iter 1 #> | | | 0% | |============== | 20% | |============================ | 40% | |========================================== | 60% | |======================================================== | 80% | |======================================================================| 100% #> iter 2 #> | | | 0% | |============== | 20% | |============================ | 40% | |========================================== | 60% | |======================================================== | 80% | |======================================================================| 100% #> iter 3 #> | | | 0% | |============== | 20% | |============================ | 40% | |========================================== | 60% | |======================================================== | 80% | |======================================================================| 100% imp #> missRanger object. Extract imputed data via $data #> - best iteration: 2 #> - best average OOB imputation error: 0.303332 ``` -------------------------------- ### summary(_<missRanger>_) - Summary Method Source: https://mayer79.github.io/missRanger/reference/index.html Summary method for missRanger objects. Provides detailed statistics about the imputation process and results. ```r summary(_<missRanger>_) ``` -------------------------------- ### Keeping Random Forests for Analysis Source: https://mayer79.github.io/missRanger/news/index.html Demonstrates how to retain the random forests generated during the imputation process by setting `keep_forests = TRUE`. This is useful when `data_only = FALSE` and allows for further analysis of the imputation models. ```R missRanger(..., keep_forests = TRUE) ``` -------------------------------- ### Display missRanger Imputation Progress Source: https://mayer79.github.io/missRanger/reference/missRanger.html Visualizes the progress of the missRanger imputation process, showing the percentage of completion for each iteration. ```r # Progress bars indicating imputation completion #> |======================================================== | 80% #> | #> |======================================================================| 100% ``` -------------------------------- ### Controlling Output: Data Only vs. Full Object Source: https://mayer79.github.io/missRanger/news/index.html Illustrates the use of the `data_only` argument in `missRanger` to control whether only the imputed data is returned or a more comprehensive object containing imputation details. `data_only = TRUE` is the default for returning just the imputed data. ```R missRanger(..., data_only = TRUE) ``` -------------------------------- ### print(_<missRanger>_) Source: https://mayer79.github.io/missRanger/reference/index.html Print Method for missRanger objects. ```APIDOC ## print(_<missRanger>_) ### Description Print Method for missRanger objects. ### Method Not applicable (function signature) ### Endpoint Not applicable (function signature) ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### pmm() - Predictive Mean Matching Source: https://mayer79.github.io/missRanger/reference/index.html Implements the Predictive Mean Matching imputation method. This method is often used as a component within more complex imputation strategies. ```r pmm() ``` -------------------------------- ### Summary of missRanger Imputation Results Source: https://mayer79.github.io/missRanger/reference/summary.missRanger.html Use this snippet to view the imputation performance and details of the best iteration after running missRanger. It shows OOB errors and the first few rows of the imputed data. ```R CO2_ <- generateNA(CO2, seed = 1) imp <- missRanger(CO2_, pmm.k = 5, data_only = FALSE, num.threads = 1) summary(imp) ``` -------------------------------- ### Display First Rows of Imputed Data Source: https://mayer79.github.io/missRanger/reference/missRanger.html Shows the initial rows of the dataset after imputation by missRanger, illustrating the structure and values of the imputed data. ```r # First rows of imputed data: #> #> Sepal.Length Sepal.Width Petal.Length Petal.Width Species #> 1 5.1 3.5 1.4 0.2 setosa #> 2 4.9 3.0 1.4 0.2 setosa #> 3 4.7 3.2 1.3 0.2 setosa ``` -------------------------------- ### Extended Output with Forests Source: https://mayer79.github.io/missRanger/articles/missRanger.html Impute missing values and retain the random forest objects for out-of-sample applications. This demonstrates keeping forests and viewing the summary of the imputation object. ```r imp <- missRanger( iris_NA, pmm.k = 5, num.trees = 100, keep_forests = TRUE, verbose = 0 ) imp ``` ```r summary(imp) ``` ```r # Out-of-sample application # saveRDS(imp, file = "imputation_model.rds") # imp <- readRDS("imputation_model.rds") predict(imp, head(iris_NA)) ``` -------------------------------- ### Perform Cox Regression and Pool Results Source: https://mayer79.github.io/missRanger/articles/working_with_censoring.html This snippet performs Cox regression on each of the 20 completed datasets and then pools the results using Rubin's rule via the `pool` function from the `mice` package. It also shows the summary of the pooled model and compares it to a Cox regression on the original data. ```R # 3. Run a Cox regression for each of the completed data sets models <- lapply(filled, function(x) coxph(Surv(time, status) ~ . - surv, x)) # 4. Pool the results by mice summary(pooled_fit <- pool(models)) # term estimate std.error statistic df p.value # 1 trt 0.231154077 0.214672763 1.0767741 105.1514 2.840454e-01 # 2 celltypesmallcell 0.805824737 0.285571376 2.8217980 114.1273 5.634607e-03 # 3 celltypeadeno 1.130585762 0.306698637 3.6863084 113.3636 3.506786e-04 # 4 celltypelarge 0.340627347 0.296740520 1.1478963 103.4753 2.536583e-01 # 5 karno -0.030623274 0.005653790 -5.4164149 106.3603 3.806255e-07 # 6 diagtime 0.001273007 0.009102230 0.1398566 108.7518 8.890320e-01 # 7 age -0.005587627 0.009379064 -0.5957554 105.3053 5.526170e-01 # 8 prior 0.005174395 0.023433186 0.2208148 112.4847 8.256369e-01 # Compare with the results on the original data summary(coxph(Surv(time, status) ~ ., veteran))$coefficients # coef exp(coef) se(coef) z Pr(>|z|) # trt 2.946028e-01 1.3425930 0.207549604 1.419433313 1.557727e-01 # celltypesmallcell 8.615605e-01 2.3668512 0.275284474 3.129709606 1.749792e-03 # celltypeadeno 1.196066e+00 3.3070825 0.300916994 3.974738536 7.045662e-05 # celltypelarge 4.012917e-01 1.4937529 0.282688638 1.419553530 1.557377e-01 # karno -3.281533e-02 0.9677173 0.005507757 -5.958020093 2.553121e-09 # diagtime 8.132051e-05 1.0000813 0.009136062 0.008901046 9.928981e-01 # age -8.706475e-03 0.9913313 0.009300299 -0.936149992 3.491960e-01 # prior 7.159360e-03 1.0071850 0.023230538 0.308187441 7.579397e-01 ``` -------------------------------- ### predict(_<missRanger>_) - Predict Method Source: https://mayer79.github.io/missRanger/reference/index.html Predict method for missRanger objects. Use this to obtain predictions from a fitted missRanger model. ```r predict(_<missRanger>_) ``` -------------------------------- ### Generate and Impute Missing Values in Iris Dataset Source: https://mayer79.github.io/missRanger/articles/missRanger.html This snippet shows how to introduce missing values into the iris dataset using `generateNA` and then impute them using `missRanger`. It requires the missRanger library to be loaded. ```R library(missRanger) set.seed(3) iris_NA <- generateNA(iris, p = 0.1) head(iris_NA) ``` ```R imp <- missRanger(iris_NA, num.trees = 100) head(imp) ``` -------------------------------- ### Copyright Disclaimer for Proprietary Employers Source: https://mayer79.github.io/missRanger/LICENSE.html A sample copyright disclaimer to be signed by an employer or school, disclaiming interest in a program. ```text Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice ``` -------------------------------- ### Compare Imputed Data with Original Data Source: https://mayer79.github.io/missRanger/reference/missRanger.html Uses the `all.equal` function to compare the imputed dataset (`imp2$data`) with another dataset (`imp1`), checking for equality. ```r all.equal(imp1, imp2$data) #> [1] TRUE ``` -------------------------------- ### Generate and Impute Missing Data in Iris Dataset Source: https://mayer79.github.io/missRanger/index.html Demonstrates how to introduce missing values into the iris dataset and then impute them using missRanger. The imputation uses predictive mean matching with k=5 and 100 random forest trees. ```r library(missRanger) set.seed(3) iris_NA <- generateNA(iris, p = 0.1) head(iris_NA) iris_filled <- missRanger(iris_NA, pmm.k = 5, num.trees = 100) head(iris_filled) ``` -------------------------------- ### Controlling Out-of-Bag Errors in missRanger Source: https://mayer79.github.io/missRanger/news/index.html Shows how to control whether out-of-bag errors are attached as an attribute to the resulting data frame using the 'returnOOB' argument. ```R missRanger(data, returnOOB = TRUE) ``` -------------------------------- ### Impute Missing Values in a Vector Source: https://mayer79.github.io/missRanger/reference/imputeUnivariate.html Demonstrates how to impute NA values in a numeric vector using the imputeUnivariate function. The function samples with replacement from the non-missing values. ```R imputeUnivariate(c(NA, 0, 1, 0, 1)) ``` -------------------------------- ### BibTeX Citation for missRanger Source: https://mayer79.github.io/missRanger/authors.html This is the BibTeX formatted citation for the missRanger R package, useful for inclusion in LaTeX documents. ```bibtex @Manual{ title = {missRanger: Fast Imputation of Missing Values}, author = {Michael Mayer}, year = {2025}, note = {R package version 2.6.2, https://mayer79.github.io/missRanger/}, url = {https://github.com/mayer79/missRanger}, } ``` -------------------------------- ### summary.missRanger Source: https://mayer79.github.io/missRanger/reference/summary.missRanger.html Provides a summary of the imputation results from a missRanger object, including the best iteration and imputation errors. ```APIDOC ## summary.missRanger ### Description Provides a summary of the imputation results from a missRanger object, including the best iteration and imputation errors. ### Usage ```R summary(object, ...) ``` ### Arguments * `object` (An object of class "missRanger") - The missRanger object to summarize. * `...` - Further arguments passed from other methods. ### Value Invisibly returns the input `object`. ### Examples ```R # Load necessary library and generate data with missing values # CO2_ <- generateNA(CO2, seed = 1) # imp <- missRanger(CO2_, pmm.k = 5, data_only = FALSE, num.threads = 1) # Summarize the imputation results # summary(imp) ``` ``` -------------------------------- ### pmm() Source: https://mayer79.github.io/missRanger/reference/index.html Predictive Mean Matching imputation method. ```APIDOC ## pmm() ### Description Predictive Mean Matching imputation method. ### Method Not applicable (function signature) ### Endpoint Not applicable (function signature) ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### missRanger() - Fast Imputation with Chained Random Forests Source: https://mayer79.github.io/missRanger/reference/index.html Fast imputation of missing values using chained random forests. This is the primary function for imputing missing data in the package. ```r missRanger() ``` -------------------------------- ### Predictive Mean Matching Function Signature Source: https://mayer79.github.io/missRanger/reference/pmm.html This is the function signature for pmm, outlining its arguments and their types. ```R pmm(xtrain, xtest, ytrain, k = 1L, seed = NULL) ``` -------------------------------- ### Calculate Nelson-Aalen Survival Estimates Source: https://mayer79.github.io/missRanger/articles/working_with_censoring.html This snippet calculates Nelson-Aalen survival probabilities for each time point in the veteran dataset. It uses the `survfit` function from the `survival` package and then extracts the time and survival probabilities. ```R library(missRanger) library(survival) library(mice) set.seed(65) head(veteran) # trt celltype time status karno diagtime age prior # 1 1 squamous 72 1 60 7 69 0 # 2 1 squamous 411 1 70 5 64 10 # 3 1 squamous 228 1 60 3 38 0 # 4 1 squamous 126 1 60 9 63 10 # 5 1 squamous 118 1 70 11 65 10 # 6 1 squamous 10 1 20 5 49 0 # 1. Calculate Nelson-Aalen survival probabilities for each time point nelson_aalen <- survfit(Surv(time, status) ~ 1, data = veteran) | summary(times = unique(veteran$time)) nelson_aalen <- nelson_aalen[c("time", "surv")] # Add it to the original data set veteran2 <- merge(veteran, nelson_aalen, all.x = TRUE, by = "time") # Add missing values to make things tricky veteran2 <- generateNA(veteran2, p = c(age = 0.1, karno = 0.1, diagtime = 0.1)) ``` -------------------------------- ### predict(_<missRanger>_) Source: https://mayer79.github.io/missRanger/reference/index.html Predict Method for missRanger objects. ```APIDOC ## predict(_<missRanger>_) ### Description Predict Method for missRanger objects. ### Method Not applicable (function signature) ### Endpoint Not applicable (function signature) ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### missRanger() Source: https://mayer79.github.io/missRanger/reference/index.html Fast Imputation of Missing Values by Chained Random Forests. ```APIDOC ## missRanger() ### Description Fast Imputation of Missing Values by Chained Random Forests. ### Method Not applicable (function signature) ### Endpoint Not applicable (function signature) ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### Multiple Imputation with missRanger Source: https://mayer79.github.io/missRanger/articles/working_with_censoring.html This code generates 20 complete datasets by imputing missing values in covariates using `missRanger`. It specifies that imputation should be performed for all variables except 'time' and 'status', using specific parameters for `pmm.k` and `num.trees`. ```R # 2. Generate 20 complete data sets, representing "time" and "status" by "surv" filled <- replicate( 20, missRanger(veteran2, . ~ . - time - status, verbose = 0, pmm.k = 10, num.trees = 100), simplify = FALSE ) ``` -------------------------------- ### pmm Source: https://mayer79.github.io/missRanger/reference/pmm.html Imputes missing values using the Predictive Mean Matching method. For each value in `xtest`, it finds the closest `k` values in `xtrain` and randomly selects one of their corresponding observed values from `ytrain` to use as the imputation. ```APIDOC ## pmm ### Description Imputes missing values using the Predictive Mean Matching method. For each value in `xtest`, it finds the closest `k` values in `xtrain` and randomly selects one of their corresponding observed values from `ytrain` to use as the imputation. ### Usage ``` pmm(xtrain, xtest, ytrain, k = 1L, seed = NULL) ``` ### Arguments * **xtrain** (vector) - Vector with predicted values in the training data. Must be numeric, logical, or factor-valued. * **xtest** (vector) - Vector as `xtrain` with predicted values in the test data. Missing values are not allowed. * **ytrain** (vector) - Vector of the observed values in the training data. Must be of same length as `xtrain`. * **k** (integer) - Number of nearest neighbours (donors) to sample from. Defaults to 1L. * **seed** (integer, optional) - Integer random seed for reproducibility. ### Value Vector of the same length as `xtest` with values from `ytrain`. ### Examples ```R pmm(xtrain = c(0.2, 0.3, 0.8), xtest = c(0.7, 0.2), ytrain = 1:3, k = 1) ``` ``` -------------------------------- ### generateNA() Source: https://mayer79.github.io/missRanger/reference/index.html Adds Missing Values to a dataset. ```APIDOC ## generateNA() ### Description Adds Missing Values to a dataset. ### Method Not applicable (function signature) ### Endpoint Not applicable (function signature) ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### Predictive Mean Matching Imputation Source: https://mayer79.github.io/missRanger/articles/missRanger.html Impute missing values using Predictive Mean Matching (PMM) with specified k and number of trees. Displays the head of the imputed data. ```r imp <- missRanger(iris_NA, pmm.k = 5, num.trees = 100, verbose = 0) head(imp) ``` -------------------------------- ### Default Formula Imputation Source: https://mayer79.github.io/missRanger/articles/missRanger.html Impute all variables using all available variables by default. This is the standard behavior when no formula is explicitly provided. ```r # Impute all variables with all (default) m <- missRanger(iris_NA, formula = . ~ ., pmm.k = 5, num.trees = 100, verbose = 0) ``` -------------------------------- ### generateNA Source: https://mayer79.github.io/missRanger/reference/generateNA.html Replaces a specified proportion of values in a vector, matrix, or data frame with NA. ```APIDOC ## Function: generateNA ### Description Takes a vector, matrix or data.frame and replaces some values by NA. ### Usage ``` generateNA(x, p = 0.1, seed = NULL) ``` ### Arguments * **x** (vector, matrix, data.frame) - The input data structure. * **p** (numeric or named numeric vector) - Proportion of missing values to add to `x`. If `x` is a data.frame, `p` can also be a vector of probabilities per column or a named vector. * **seed** (integer, optional) - An integer seed for reproducibility. ### Value Returns the input `x` with missing values introduced. ### Examples ```R generateNA(1:10, p = 0.5) # Expected output: A vector with approximately 50% NA values. head(generateNA(iris, p = 0.2)) # Expected output: The first few rows of the iris dataset with approximately 20% NA values introduced. ``` ``` -------------------------------- ### Basic Imputation with missRanger Source: https://mayer79.github.io/missRanger/articles/missRanger.html Imputes missing values in the 'iris_NA' dataset, specifying variables for imputation and predictor variables. Uses 100 trees and a PMM k value of 5. ```r m <- missRanger(iris_NA, Sepal.Length + Species ~ Species, pmm.k = 5, num.trees = 100) ``` -------------------------------- ### imputeUnivariate() - Univariate Imputation Source: https://mayer79.github.io/missRanger/reference/index.html Performs univariate imputation on a dataset. This is a simpler imputation method compared to chained random forests. ```r imputeUnivariate() ``` -------------------------------- ### imputeUnivariate() Source: https://mayer79.github.io/missRanger/reference/index.html Performs Univariate Imputation on a dataset. ```APIDOC ## imputeUnivariate() ### Description Performs Univariate Imputation on a dataset. ### Method Not applicable (function signature) ### Endpoint Not applicable (function signature) ### Parameters (No specific parameters documented in the source) ### Request Example (No request example provided) ### Response (No response details provided) ``` -------------------------------- ### Imputation with Case Weights in missRanger Source: https://mayer79.github.io/missRanger/articles/missRanger.html Imputes missing values in 'iris_NA' using case weights derived from the number of non-missing values per row. This reduces the impact of rows with many missing entries. ```r m <- missRanger( iris_NA, num.trees = 100, pmm.k = 5, case.weights = rowSums(!is.na(iris_NA)) ) ``` -------------------------------- ### imputeUnivariate Source: https://mayer79.github.io/missRanger/reference/imputeUnivariate.html Fills missing values of a vector, matrix or data frame by sampling with replacement from the non-missing values. For data frames, this sampling is done within column. ```APIDOC ## imputeUnivariate ### Description Fills missing values of a vector, matrix or data frame by sampling with replacement from the non-missing values. For data frames, this sampling is done within column. ### Usage ```R imputeUnivariate(x, v = NULL, seed = NULL) ``` ### Arguments * **x** (vector, matrix or data frame) - The input data structure. * **v** (character vector, optional) - A character vector of column names to impute (only relevant if `x` is a data frame). The default `NULL` imputes all columns. * **seed** (integer, optional) - An integer seed for reproducibility. ### Value `x` with imputed values. ### Examples ```R # Impute missing values in a vector imputeUnivariate(c(NA, 0, 1, 0, 1)) # Impute missing values in a data frame (iris dataset) head(imputeUnivariate(generateNA(iris))) ``` ``` -------------------------------- ### Univariate Imputation with Formula Source: https://mayer79.github.io/missRanger/reference/missRanger.html Imputes 'Species' and 'Sepal.Width' using other variables in the 'iris2' dataset. This method is suitable for simple imputation tasks where specific variables need to be imputed. ```r imp3 <- missRanger(iris2, Species + Sepal.Width ~ 1) ``` -------------------------------- ### generateNA() - Adds Missing Values Source: https://mayer79.github.io/missRanger/reference/index.html Adds missing values to a dataset. Use this function to simulate missing data for testing imputation methods. ```r generateNA() ``` -------------------------------- ### predict.missRanger Source: https://mayer79.github.io/missRanger/reference/predict.missRanger.html Imputes missing values in a new dataset ('newdata') using a trained 'missRanger' object. Supports multivariate and univariate imputation, with options for controlling iterations, threads, and random seeds. ```APIDOC ## predict.missRanger ### Description Impute missing values on `newdata` based on an object of class "missRanger". For multivariate imputation, use `missRanger(..., keep_forests = TRUE)`. For univariate imputation, no forests are required. This can be enforced by `predict(..., iter = 0)` or via `missRanger(. ~ 1, ...)`. Note that out-of-sample imputation works best for rows in `newdata` with only one missing value (counting only missings in variables used as covariates in random forests). We call this the "easy case". In the "hard case", even multiple iterations (set by `iter`) can lead to unsatisfactory results. ### Method S3 method for class 'missRanger' ### Arguments * **object** ('missRanger' object). * **newdata** (A `data.frame` with missing values to impute). * **pmm.k** (Number of candidate predictions of the original dataset for predictive mean matching (PMM). By default the same value as during fitting.). * **iter** (Number of iterations for "hard case" rows. 0 for univariate imputation.). * **num.threads** (Number of threads used by ranger's predict function. The default `NULL` uses all threads.). * **seed** (Integer seed used for initial univariate imputation and PMM.). * **verbose** (Should info be printed? (1 = yes/default, 0 for no).). * **...** (Passed to the predict function of ranger.). ### Details The out-of-sample algorithm works as follows: 1. Impute univariately all relevant columns by randomly drawing values from the original unimputed data. This step will only impact "hard case" rows. 2. Replace univariate imputations by predictions of random forests. This is done sequentially over variables, where the variables are sorted to minimize the impact of univariate imputations. Optionally, this is followed by predictive mean matching (PMM). 3. Repeat Step 2 for "hard case" rows multiple times. ### Examples ```R iris2 <- generateNA(iris, seed = 20, p = c(Sepal.Length = 0.2, Species = 0.1)) imp <- missRanger(iris2, pmm.k = 5, num.trees = 100, keep_forests = TRUE, seed = 2) predict(imp, head(iris2), seed = 3) ``` ``` -------------------------------- ### Univariate Imputation with missRanger Source: https://mayer79.github.io/missRanger/articles/missRanger.html Imputes all variables in the 'iris_NA' dataset univariately, suppressing verbose output. ```r m <- missRanger(iris_NA, . ~ 1, verbose = 0) ``` -------------------------------- ### missRanger Function Source: https://mayer79.github.io/missRanger/reference/missRanger.html The missRanger function imputes missing values in a data frame using chained random forests. It supports various parameters to control the imputation process, including formula specification, predictive mean matching, and parameters passed to the underlying ranger package. ```APIDOC ## missRanger() ### Description Performs fast imputation of missing values by chained random forests. It utilizes the 'ranger' package and offers options for predictive mean matching to improve imputation quality. ### Usage ```R missRanger( data, formula = . ~ ., pmm.k = 0L, num.trees = 500, mtry = NULL, min.node.size = NULL, min.bucket = NULL, max.depth = NULL, replace = TRUE, sample.fraction = if (replace) 1 else 0.632, case.weights = NULL, num.threads = NULL, save.memory = FALSE, maxiter = 10L, seed = NULL, verbose = 1, returnOOB = FALSE, data_only = !keep_forests, keep_forests = FALSE, ... ) ``` ### Arguments * **data** (data.frame) - A data frame with missing values to impute. * **formula** (formula) - A two-sided formula specifying variables to be imputed (left hand side) and variables used to impute (right hand side). Defaults to `. ~ .`, i.e., use all variables to impute all variables. For instance, if all variables (with missings) should be imputed by all variables except variable "ID", use `. ~ . - ID`. Note that a "." is evaluated separately for each side of the formula. Further note that variables with missings must appear in the left hand side if they should be used on the right hand side. * **pmm.k** (integer) - Number of candidate non-missing values to sample from in the predictive mean matching steps. 0 to avoid this step. * **num.trees** (integer) - Number of trees passed to `ranger::ranger()`. * **mtry** (integer or function) - Number of covariates considered per split. The default `NULL` equals the rounded down root of the number of features. Can be a function, e.g., `function(p) trunc(p/3)`. Passed to `ranger::ranger()`. Note that during the first iteration, the number of features is growing. Thus, a fixed value can lead to an error. Using a function like `function(p) min(p, 2)` will fix such problem. * **min.node.size** (integer) - Minimal node size passed to `ranger::ranger()`. By default 1 for classification and 5 for regression. * **min.bucket** (integer) - Minimal terminal node size passed to `ranger::ranger()`. The default `NULL` means 1. * **max.depth** (integer) - Maximal tree depth passed to `ranger::ranger()`. `NULL` means unlimited depth. 1 means single split trees. * **replace** (logical) - Sample with replacement passed to `ranger::ranger()`. * **sample.fraction** (numeric) - Fraction of rows per tree passed to `ranger::ranger()`. The default: use all rows when `replace = TRUE` and 0.632 otherwise. * **case.weights** (numeric vector) - Optional case weights passed to `ranger::ranger()`. * **num.threads** (integer) - Number of threads passed to `ranger::ranger()`. The default `NULL` uses all threads. * **save.memory** (logical) - Slow but memory saving mode of `ranger::ranger()`. * **maxiter** (integer) - Maximum number of iterations. * **seed** (integer) - Integer seed. * **verbose** (integer) - A value in 0, 1, 2 controlling the verbosity. * **returnOOB** (logical) - Should the final average OOB prediction errors be added as data attribute "oob"? Only relevant when `data_only = TRUE`. * **data_only** (logical) - If `TRUE` (default), only the imputed data is returned. Otherwise, a "missRanger" object with additional information is returned. * **keep_forests** (logical) - Should the random forests of the last relevant iteration be returned? The default is `FALSE`. Setting this option will use a lot of memory. Only relevant when `data_only = TRUE`. * **...** - Additional arguments passed to `ranger::ranger()`. Not all make sense. ### Value If `data_only = TRUE` an imputed `data.frame`. Otherwise, a "missRanger" object with the following elements: * `data`: The imputed data. * `data_raw`: The original data provided. * `forests`: When `keep_forests = TRUE`, a list of "ranger" models used to generate the imputed data. `NULL` otherwise. * `to_impute`: Variables to be imputed (in this order). * `impute_by`: Variables used for imputation. * `best_iter`: Best iteration. * `pred_errors`: Per-iteration OOB prediction errors (1 - R^2 for regression, classification error otherwise). * `mean_pred_errors`: Per-iteration averages of OOB prediction errors. * `pmm.k`: Same as input `pmm.k`. ``` -------------------------------- ### missRanger Function Signature Source: https://mayer79.github.io/missRanger/reference/missRanger.html The primary function for imputing missing values. It takes a data frame and a formula to specify which variables to impute and which to use for imputation. Various parameters control the random forest algorithm and imputation process. ```R missRanger( data, formula = . ~ ., pmm.k = 0L, num.trees = 500, mtry = NULL, min.node.size = NULL, min.bucket = NULL, max.depth = NULL, replace = TRUE, sample.fraction = if (replace) 1 else 0.632, case.weights = NULL, num.threads = NULL, save.memory = FALSE, maxiter = 10L, seed = NULL, verbose = 1, returnOOB = FALSE, data_only = !keep_forests, keep_forests = FALSE, ... ) ``` -------------------------------- ### Add NA to a Vector Source: https://mayer79.github.io/missRanger/reference/generateNA.html Adds NA values to a numeric vector. Specify the proportion of NAs to introduce. ```R generateNA(1:10, p = 0.5) ``` -------------------------------- ### Targeted Formula Imputation Source: https://mayer79.github.io/missRanger/articles/missRanger.html Impute a specific variable ('Sepal.Length') using only the specified predictor variables ('Species'). Note that univariate imputation occurs if predictors have missing values. ```r # Impute Sepal.Length by Species (or not?) m <- missRanger(iris_NA, Sepal.Length ~ Species, pmm.k = 5, num.trees = 100) head(m) ```