### Loading Libraries and Data for `fill_NA_N` Example Source: https://polkas.github.io/miceFast/reference/fill_NA_N.html Loads necessary libraries (miceFast, dplyr, data.table) and the 'air_miss' dataset for demonstrating the `fill_NA_N` function. ```R library(miceFast) library(dplyr) library(data.table) data(air_miss) ``` -------------------------------- ### Install miceFast Development Version from GitHub Source: https://polkas.github.io/miceFast/index.html Installation of the development version of miceFast directly from its GitHub repository using the devtools package. ```r # install.packages("devtools") devtools::install_github("polkas/miceFast") ``` -------------------------------- ### Load and Inspect Example Data Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Loads the `air_miss` dataset, which is an extended version of `airquality` with additional columns, and displays its structure. ```R data(air_miss) str(air_miss) ``` -------------------------------- ### Example Usage of `fill_NA` Source: https://polkas.github.io/miceFast/reference/fill_NA.html Demonstrates loading necessary libraries and data for using the `fill_NA` function. ```R library(miceFast) library(dplyr) #> #> Attaching package: ‘dplyr’ #> The following objects are masked from ‘package:stats’: #> #> filter, lag #> The following objects are masked from ‘package:base’: #> #> intersect, setdiff, setequal, union library(data.table) #> #> Attaching package: ‘data.table’ #> The following objects are masked from ‘package:dplyr’: #> #> between, first, last data(air_miss) ``` -------------------------------- ### Install miceFast from CRAN Source: https://polkas.github.io/miceFast/index.html Standard installation of the miceFast package from the Comprehensive R Archive Network (CRAN). ```r install.packages("miceFast") ``` -------------------------------- ### Quick Example: Data Preparation and Visualization with dplyr Source: https://polkas.github.io/miceFast/index.html Loads necessary libraries, sample data, and visualizes the structure of missing data using upset_NA. Selects core variables for regression analysis. ```r library(miceFast) library(dplyr) data(air_miss) # Visualize the NA structure upset_NA(air_miss, 6) # Select the 4 core variables for regression: Ozone ~ Solar.R + Wind + Temp # Ozone has 37 NAs, Solar.R has 7 NAs, Wind and Temp are complete. df <- air_miss[, c("Ozone", "Solar.R", "Wind", "Temp")] ``` -------------------------------- ### Calculate VIF with data.table (Basic) Source: https://polkas.github.io/miceFast/reference/VIF.html Example of using the VIF function with a data.table to calculate basic VIF values. Ensure 'miceFast' and 'data.table' libraries are loaded. ```R library(miceFast) library(data.table) airquality2 <- airquality airquality2$Temp2 <- airquality2$Temp**2 airquality2$Month <- factor(airquality2$Month) data_DT <- data.table(airquality2) data_DT[, .(vifs = VIF( x = .SD, posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp", "Month", "Day", "Temp2"), correct = FALSE ))][["vifs.V1"]] ``` -------------------------------- ### Pooled results from 3 imputed datasets Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Example output showing pooled regression results from 3 imputed datasets, including coefficients, standard errors, p-values, and pooling diagnostics. ```text ## Pooled results from 3 imputed datasets ## Rubin's rules with Barnard-Rubin df adjustment ## Complete-data df: 148 ## ## Coefficients: ## term estimate std.error statistic df p.value conf.low conf.high ## (Intercept) -63.965 22.6779 -2.821 38.59 7.531e-03 -109.851 -18.079 ## Wind -2.998 0.6121 -4.898 61.02 7.451e-06 -4.222 -1.774 ## Temp 1.750 0.2387 7.329 47.51 2.441e-09 1.270 2.230 ## ## Pooling diagnostics: ## term ubar b t riv lambda fmi ## (Intercept) 418.10247 72.138255 514.2868 0.2300 0.1870 0.2261 ## Wind 0.32578 0.036664 0.3747 0.1501 0.1305 0.1576 ## Temp 0.04785 0.006863 0.0570 0.1913 0.1606 0.1938 ## Pooled results from 5 imputed datasets ## Rubin's rules with Barnard-Rubin df adjustment ## Complete-data df: 148 ## ## Coefficients: ## term estimate std.error statistic df p.value conf.low conf.high ``` -------------------------------- ### Basic Imputation with dplyr Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Demonstrates basic imputation for continuous (lm_bayes) and categorical (lda) variables using dplyr. Ensure the 'micefast' package is installed and loaded. ```R data(air_miss) result <- air_miss %>% # Continuous variable: Bayesian linear model (stochastic) mutate(Ozone_imp = fill_NA( x = ., model = "lm_bayes", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp") )) %>% # Categorical variable: LDA mutate(x_char_imp = fill_NA( x = ., model = "lda", posit_y = "x_character", posit_x = c("Wind", "Temp") )) head(result[, c("Ozone", "Ozone_imp", "x_character", "x_char_imp")]) ``` -------------------------------- ### Calculate VIF with data.table (Corrected) Source: https://polkas.github.io/miceFast/reference/VIF.html Example of using the VIF function with a data.table to calculate corrected VIF values. Ensure 'miceFast' and 'data.table' libraries are loaded. ```R library(miceFast) library(data.table) data_DT[, .(vifs = VIF( x = .SD, posit_y = 1, posit_x = c(2, 3, 4, 5, 6, 7), correct = TRUE ))][["vifs.V1"]] ``` -------------------------------- ### Basic MI Workflow with miceFast Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Demonstrates the three-step Multiple Imputation workflow using miceFast. This includes creating multiple completed datasets with `fill_NA`, fitting the analysis model on each dataset, and pooling the results using `pool()`. ```R data(air_miss) # Step 1: Create m = 10 completed datasets m <- 10 completed <- lapply(1:m, function(i) { air_miss %>% mutate( Ozone_imp = fill_NA( x = ., model = "lm_bayes", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp") ) ) }) # Step 2: Fit the analysis model on each fits <- lapply(completed, function(d) { lm(Ozone_imp ~ Wind + Temp, data = d) }) # Step 3: Pool using Rubin's rules pool_result <- pool(fits) pool_result ``` ```R ## Pooled results from 10 imputed datasets ## Rubin's rules with Barnard-Rubin df adjustment ## ## term estimate std.error statistic df p.value ## (Intercept) -58.153 24.8186 -2.343 55.99 2.270e-02 ## Wind -3.510 0.6549 -5.359 80.60 7.764e-07 ## Temp 1.728 0.2662 6.494 55.16 2.511e-08 ``` ```R # Detailed summary with confidence intervals summary(pool_result) ``` ```R ## Pooled results from 10 imputed datasets ## Rubin's rules with Barnard-Rubin df adjustment ## Complete-data df: 148 ``` -------------------------------- ### Show Class and Object Information Source: https://polkas.github.io/miceFast/reference/Rcpp_miceFast-class.html Displays the structure and available methods of the 'miceFast' C++ class and shows an instance of the class. ```R #showClass("Rcpp_miceFast") show(miceFast) #> C++ class 'miceFast' <0x600000ca2b00> #> Constructors: #> miceFast() #> #> Fields: No public fields exposed by this class #> #> Methods: #> arma::Mat get_data() #> #> arma::Col get_g() #> #> arma::Col get_index() #> #> std::__1::basic_string, std::__1::allocator> get_model(int) #> #> std::__1::basic_string, std::__1::allocator> get_models(int) #> #> double get_ridge() #> #> arma::Col get_w() #> #> Rcpp::List impute(std::__1::basic_string, std::__1::allocator>, int, arma::Col) #> #> Rcpp::List impute_N(std::__1::basic_string, std::__1::allocator>, int, arma::Col, int) #> #> bool is_sorted_byg() #> #> void set_data(arma::Mat) #> #> void set_g(arma::Col) #> #> void set_ridge(double) #> #> void set_w(arma::Col) #> #> void sort_byg() #> #> void update_var(int, arma::Col) #> #> arma::Col vifs(int, arma::Col) #> #> std::__1::vector> which_updated() #> new(miceFast) #> C++ object <0x139026b10> of class 'miceFast' <0x600000ca2b00> ``` -------------------------------- ### Initialization and Finalization Methods Source: https://polkas.github.io/miceFast/reference/Rcpp_miceFast-class.html Basic initialization and finalization methods for the object. ```APIDOC ## initialize(...) ### Description Initializes the object. ### Method `initialize()` ``` ```APIDOC ## finalize() ### Description Finalizes the object. ### Method `finalize()` ``` -------------------------------- ### FMI Results from Pilot Imputation Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Displays the Fraction of Missing Information (FMI) for each term in the pooled regression model from a pilot imputation. This output is used to guide the selection of the number of imputations. ```R data.frame(term = pilot_pool$term, fmi = round(pilot_pool$fmi, 3)) ``` -------------------------------- ### Load and Prepare air_miss Dataset in R Source: https://polkas.github.io/miceFast/reference/air_miss.html This code snippet demonstrates how to load the airquality dataset, augment it with additional variables like 'Intercept', 'index', 'weights', and 'groups', and then convert it into a data.table format. It also shows how to create character and factor versions of ozone data and a logical variable indicating if ozone is above its mean. ```R library(data.table) data(airquality) data <- cbind(as.matrix(airquality[, -5]), Intercept = 1, index = 1:nrow(airquality), # a numeric vector - positive values weights = rnorm(nrow(airquality), 1, 0.01), # months as groups groups = airquality[, 5] ) # data.table air_miss <- data.table(data) air_miss$groups <- factor(air_miss$groups) # Distribution of Ozone - close to log-normal # hist(air_miss$Ozone) # Additional vars # Make a character variable to show package capabilities air_miss$x_character <- as.character(cut(air_miss$Solar.R, seq(0, 350, 70))) # Discrete version of dependent variable air_miss$Ozone_chac <- as.character(cut(air_miss$Ozone, seq(0, 160, 20))) air_miss$Ozone_f <- cut(air_miss$Ozone, seq(0, 160, 20)) air_miss$Ozone_high <- air_miss$Ozone > mean(air_miss$Ozone, na.rm = T) ``` -------------------------------- ### Multiple Imputation with Rubin's Rules using miceFast Source: https://polkas.github.io/miceFast/index.html Demonstrates a Multiple Imputation (MI) workflow using Rubin's rules. It imputes missing values in 'Solar.R' and 'Ozone' sequentially, leveraging the freshly imputed 'Solar.R' for 'Ozone' imputation, and prepares for model fitting and pooling. ```r # MI with Rubin's rules: impute m = 10 datasets, fit model, pool. # Impute Solar.R first (predictors fully observed), then Ozone # (can now use the freshly imputed Solar.R). This sequential order ``` -------------------------------- ### Visualize NA Values with upset_NA Source: https://polkas.github.io/miceFast/reference/upset_NA.html Use this function to visualize the intersections of NA values in a dataset. Ensure the UpSetR package is installed and loaded. The function accepts the data frame and an optional integer for the number of sets. ```R if (requireNamespace("UpSetR", quietly = TRUE)) { library(UpSetR) upset_NA(airquality) upset_NA(air_miss, 6) } ``` -------------------------------- ### Quick Multiple Imputation Recipe Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html A concise 10-line R code snippet demonstrating the core steps of multiple imputation: imputing missing values using `fill_NA`, fitting a linear model to each imputed dataset, and pooling the results with Rubin's rules. ```r data(air_miss) # 1. Impute m = 10 completed datasets completed <- lapply(1:10, function(i) { air_miss %>% mutate(Ozone_imp = fill_NA(x = ., model = "lm_bayes", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp"))) }) # 2. Fit the analysis model on each fits <- lapply(completed, function(d) lm(Ozone_imp ~ Wind + Temp, data = d)) # 3. Pool using Rubin's rules summary(pool(fits)) ``` -------------------------------- ### Compare Imputation Methods for Missing Data Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Compares results from different missing data handling techniques: complete cases (listwise deletion), mean imputation, deterministic regression imputation, and proper multiple imputation (MI). Requires the 'micefast' package for imputation functions. ```R data(air_miss) set.seed(2025) # 1. Complete cases (listwise deletion). Unbiased under MCAR. fit_cc <- lm(Ozone ~ Wind + Temp, data = air_miss[complete.cases(air_miss[, c("Ozone", "Wind", "Temp")]), ]) ci_cc <- confint(fit_cc) # 2. Mean imputation. Biased; underestimates variance. air_mean <- air_miss air_mean$Ozone[is.na(air_mean$Ozone)] <- mean(air_mean$Ozone, na.rm = TRUE) fit_mean <- lm(Ozone ~ Wind + Temp, data = air_mean) ci_mean <- confint(fit_mean) # 3. Deterministic regression imputation (lm_pred). No residual noise. air_pred <- air_miss %>% mutate(Ozone_imp = fill_NA( x = ., model = "lm_pred", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp") )) fit_pred <- lm(Ozone_imp ~ Wind + Temp, data = air_pred) ci_pred <- confint(fit_pred) # 4. Proper MI with Rubin's rules (lm_bayes, m = 20) completed <- lapply(1:20, function(i) { air_miss %>% mutate(Ozone_imp = fill_NA( x = ., model = "lm_bayes", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp") )) }) fits <- lapply(completed, function(d) lm(Ozone_imp ~ Wind + Temp, data = d)) pool_s <- summary(pool(fits)) ``` -------------------------------- ### Basic Usage of `naive_fill_NA` Source: https://polkas.github.io/miceFast/reference/naive_fill_NA.html Demonstrates the basic application of the `naive_fill_NA` function on a dataset with missing values. It's recommended to run this function separately for each categorical variable. ```R library(miceFast) data(air_miss) naive_fill_NA(air_miss) ``` -------------------------------- ### Mimic Iterative FCS with OOP Interface Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html This code demonstrates how to mimic the iterative Fully Conditional Specification (FCS) algorithm using the OOP interface of miceFast. It involves saving original NA values, initializing them, and then iteratively updating variables using specified imputation models. This approach is useful for complex missing data patterns. ```R # Save which cells are originally NA na1 <- is.na(mat[, 1]); na2 <- is.na(mat[, 2]); na3 <- is.na(mat[, 3]) # Initialise NAs (e.g. column means) so predictors are always complete for (j in seq_len(ncol(mat))) { na_j <- is.na(mat[, j]) if (any(na_j)) mat[na_j, j] <- mean(mat[!na_j, j]) } model$set_data(mat) for (iter in 1:5) { col1 <- model$get_data()[, 1]; col1[na1] <- NaN; model$update_var(1, col1) model$update_var(1, model$impute("lm_bayes", 1, c(2, 3, 4))$imputations) col2 <- model$get_data()[, 2]; col2[na2] <- NaN; model$update_var(2, col2) model$update_var(2, model$impute("lm_bayes", 2, c(1, 3, 4))$imputations) col3 <- model$get_data()[, 3]; col3[na3] <- NaN; model$update_var(3, col3) model$update_var(3, model$impute("lda", 3, c(1, 2, 4))$imputations) } ``` -------------------------------- ### Reference for HowManyImputations Package Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Provides a reference to the R package 'howManyImputations' and its implementation for calculating the required number of imputations based on FMI. ```R # For the exact formula and its derivation see: # von Hippel (2020) "How many imputations do you need?", Sociological Methods & Research # R implementation: install.packages("howManyImputations") ``` -------------------------------- ### Basic Imputation with miceFast Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Demonstrates single and multiple imputation using linear models. Use `update_var` to apply imputations and `which_updated` to check updated columns. ```R data <- cbind(as.matrix(airquality[, 1:4]), intercept = 1, index = 1:nrow(airquality)) model <- new(miceFast) model$set_data(data) # Single imputation with linear model (col 1 = Ozone) model$update_var(1, model$impute("lm_pred", 1, 5)$imputations) # Averaged multiple imputation for Solar.R (col 2, Bayesian, k=10 draws) model$update_var(2, model$impute_N("lm_bayes", 2, c(1, 3, 4, 5), k = 10)$imputations) model$which_updated() ``` ```R ## [1] 1 2 ``` ```R head(model$get_data(), 4) ``` ```R ## [,1] [,2] [,3] [,4] [,5] [,6] ## [1,] 41 190 7.4 67 1 1 ## [2,] 36 118 8.0 72 1 2 ## [3,] 12 149 12.6 74 1 3 ## [4,] 18 313 11.5 62 1 4 ``` -------------------------------- ### Full MI Workflow with OOP in miceFast Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Drives the full multiple imputation loop using the OOP interface. Each iteration creates a new model, imputes missing values, and returns the completed matrix in original row order. Supports 'lm_bayes' and 'pmm' models. ```R data(air_miss) # Prepare a numeric matrix with an intercept and row index mat <- cbind( as.matrix(air_miss[, c("Ozone", "Solar.R", "Wind", "Temp")]), intercept = 1, index = seq_len(nrow(air_miss)) ) groups <- as.numeric(air_miss$groups) impute_oop <- function(mat, groups) { m <- new(miceFast) m$set_data(mat + 0) # copy. set_data uses the matrix by reference. m$set_g(groups) # col 1 = Ozone, col 2 = Solar.R, col 3 = Wind, col 4 = Temp, col 5 = intercept m$update_var(1, m$impute("lm_bayes", 1, c(2, 3, 4))$imputations) m$update_var(2, m$impute("lm_bayes", 2, c(3, 4, 5))$imputations) completed <- m$get_data()[order(m$get_index()), ] as.data.frame(completed) } set.seed(2025) completed <- lapply(1:10, function(i) impute_oop(mat, groups)) fits <- lapply(completed, function(d) lm(V1 ~ V3 + V4, data = d)) pool(fits) ``` ```R ## Pooled results from 10 imputed datasets ## Rubin's rules with Barnard-Rubin df adjustment ## ## term estimate std.error statistic df p.value ## (Intercept) -69.010 25.8410 -2.671 62.19 9.651e-03 ``` -------------------------------- ### Perform Naive Imputation Source: https://polkas.github.io/miceFast/index.html This snippet demonstrates a quick baseline for imputation using the 'naive_fill_NA' function. Note that this method is biased as it does not account for relationships between variables. ```R # Quick baseline. Biased; does not account for relationships between variables. naive_fill_NA(air_miss) ``` -------------------------------- ### S3 method for 'miceFast_pool' class Source: https://polkas.github.io/miceFast/reference/summary.miceFast_pool.html This is the signature for the summary method applied to objects of class 'miceFast_pool'. It is used to display detailed pooling diagnostics. ```R # S3 method for class 'miceFast_pool' summary(object, ...) ``` -------------------------------- ### Display Rcpp_corrData Class Structure Source: https://polkas.github.io/miceFast/reference/Rcpp_corrData-class.html Use `showClass` to display the structure of the Rcpp_corrData class, including its constructors and methods. This helps in understanding how to instantiate and use the class. ```R #showClass("Rcpp_corrData") show(corrData) #> C++ class 'corrData' <0x600000ca3400> #> Constructors: #> corrData(int, arma::Col, arma::Mat) #> corrData(int, int, arma::Col, arma::Mat) #> #> Fields: No public fields exposed by this class #> #> Methods: #> arma::Mat fill(std::__1::basic_string, std::__1::allocator>) #> ``` -------------------------------- ### Load Required Libraries and Set Seed Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Loads the miceFast package along with dplyr, data.table, and ggplot2. Sets a seed for reproducibility. ```R library(miceFast) library(dplyr) library(data.table) library(ggplot2) set.seed(123456) ``` -------------------------------- ### MI with PMM using OOP interface Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Implements Multiple Imputation using Predictive Mean Matching (PMM) via the OOP interface of miceFast. This method ensures imputed values are from the observed data. ```r data(air_miss) dat <- as.matrix(air_miss[, c("Ozone", "Solar.R", "Wind", "Temp")]) dat <- cbind(dat, Intercept = 1) m <- 10 completed <- lapply(1:m, function(i) { model <- new(miceFast) model$set_data(dat + 0) # copy. set_data uses the matrix by reference. # impute("pmm", ...) draws from the Bayesian posterior and matches to nearest observed value model$update_var(1, model$impute("pmm", 1, c(3, 4, 5))$imputations) d <- as.data.frame(model$get_data()) colnames(d) <- c("Ozone", "Solar.R", "Wind", "Temp", "Intercept") d }) fits_pmm <- lapply(completed, function(d) { lm(Ozone ~ Wind + Temp, data = d) }) pool(fits_pmm) ``` -------------------------------- ### Comparing imputation models with fill_NA_N Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Compares different imputation strategies (lm_bayes, lm_noise, pmm, lm_pred) by generating single filled-in datasets using fill_NA_N for quick sensitivity checks. ```r data(air_miss) air_sensitivity <- air_miss %>% mutate( Ozone_bayes = fill_NA(x = ., model = "lm_bayes", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp")), Ozone_noise = fill_NA(x = ., model = "lm_noise", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp")), Ozone_pmm = fill_NA_N(x = ., model = "pmm", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp"), k = 20), Ozone_pred = fill_NA(x = ., model = "lm_pred", posit_y = "Ozone", posit_x = c("Solar.R", "Wind", "Temp")) ) compare_imp(air_sensitivity, origin = "Ozone", target = c("Ozone_bayes", "Ozone_noise", "Ozone_pmm", "Ozone_pred")) ``` -------------------------------- ### Model Information Methods Source: https://polkas.github.io/miceFast/reference/Rcpp_miceFast-class.html Methods for retrieving information about quantitative models. ```APIDOC ## get_models(...) ### Description Gets possible quantitative models for a certain type of dependent variable. ### Method `get_models(int dependent_var_type) -> std::string` ### Parameters * **dependent_var_type** (int) - The type of the dependent variable. ### Returns A string describing the possible quantitative models. ``` ```APIDOC ## get_model(...) ### Description Gets a recommended quantitative model for a certain type of dependent variable. ### Method `get_model(int dependent_var_type) -> std::string` ### Parameters * **dependent_var_type** (int) - The type of the dependent variable. ### Returns A string describing the recommended quantitative model. ``` -------------------------------- ### Ridge and Index Methods Source: https://polkas.github.io/miceFast/reference/Rcpp_miceFast-class.html Methods for setting and retrieving the ridge disturbance and index. ```APIDOC ## set_ridge(...) ### Description Provides the ridge disturbance, which is added to the diagonal of XX. ### Method `set_ridge(double ridge = 1e-6)` ### Parameters * **ridge** (double) - The ridge disturbance value. Defaults to 1e-6. ``` ```APIDOC ## get_ridge(...) ### Description Retrieves the ridge disturbance. ### Method `get_ridge() -> double` ### Returns The ridge disturbance value. ``` ```APIDOC ## get_index(...) ### Description Gets the index. ### Method `get_index() -> arma::Col` ### Returns A vector of unsigned integers representing the index. ``` -------------------------------- ### Data Input Methods Source: https://polkas.github.io/miceFast/reference/Rcpp_miceFast-class.html Methods for providing and retrieving data, grouping variables, and weighting variables. ```APIDOC ## set_data(...) ### Description Provides data by reference as a numeric matrix. ### Method `set_data(arma::Mat data)` ### Parameters * **data** (arma::Mat) - The numeric matrix representing the data. ``` ```APIDOC ## set_g(...) ### Description Provides a grouping variable by reference as a numeric vector without NA values. ### Method `set_g(arma::Col g)` ### Parameters * **g** (arma::Col) - The numeric vector representing the grouping variable (positive values). ``` ```APIDOC ## set_w(...) ### Description Provides a weighting variable by reference as a numeric vector without NA values. ### Method `set_w(arma::Col w)` ### Parameters * **w** (arma::Col) - The numeric vector representing the weighting variable (positive values). ``` ```APIDOC ## get_data(...) ### Description Retrieves the data. ### Method `get_data() -> arma::Mat` ### Returns A numeric matrix representing the data. ``` ```APIDOC ## get_w(...) ### Description Retrieves the weighting variable. ### Method `get_w() -> arma::Col` ### Returns A numeric vector representing the weighting variable. ``` ```APIDOC ## get_g(...) ### Description Retrieves the grouping variable. ### Method `get_g() -> arma::Col` ### Returns A numeric vector representing the grouping variable. ``` -------------------------------- ### summary(__) Source: https://polkas.github.io/miceFast/reference/index.html Summary method for pooled Multiple Imputation (MI) results, providing a concise overview. ```APIDOC ## summary(__) ### Description Summary method for pooled MI results. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters (Specific parameters not detailed in the source text) ### Request Example (Example not provided in the source text) ### Response (Specific response details not provided in the source text) ``` -------------------------------- ### Imputation with Weights and Groups in miceFast Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Shows how to set and use weighting and grouping variables for imputation. The original row order can be recovered using `get_index()` after sorting. ```R data <- cbind(as.matrix(airquality[, -5]), intercept = 1, index = 1:nrow(airquality)) weights <- rgamma(nrow(data), 3, 3) groups <- as.numeric(airquality[, 5]) model <- new(miceFast) model$set_data(data) model$set_w(weights) model$set_g(groups) model$update_var(1, model$impute("lm_pred", 1, 6)$imputations) model$update_var(2, model$impute_N("lm_bayes", 2, c(1, 3, 4, 5, 6), k = 10)$imputations) # Recover original row order head(cbind(model$get_data(), model$get_g(), model$get_w())[order(model$get_index()), ], 4) ``` ```R ## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] ## [1,] 41 190 7.4 67 1 1 1 5 0.5007903 ## [2,] 36 118 8.0 72 2 1 2 5 0.3379412 ## [3,] 12 149 12.6 74 3 1 3 5 0.6301132 ## [4,] 18 313 11.5 62 4 1 4 5 0.7454949 ``` -------------------------------- ### Convert Factors to Matrix for Imputation Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Demonstrates converting factors in a data frame to a matrix using `model.matrix()`. This is necessary because R matrices can only hold one data type. ```R mtcars$cyl <- factor(mtcars$cyl) model.matrix(~ ., data = mtcars, na.action = "na.pass") ``` -------------------------------- ### Load Libraries and Set Seed Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Loads necessary R libraries for data manipulation, plotting, and imputation. Sets a seed for reproducible random number generation. ```r library(miceFast) library(dplyr) library(ggplot2) set.seed(2025) ``` -------------------------------- ### Function Signature for `fill_NA_N` Source: https://polkas.github.io/miceFast/reference/fill_NA_N.html Defines the main function signature and its S3 methods for different data classes (data.frame, data.table, matrix). ```R fill_NA_N( x, model, posit_y, posit_x, w = NULL, logreg = FALSE, k = 10, ridge = 1e-06 ) # S3 method for class 'data.frame' fill_NA_N( x, model, posit_y, posit_x, w = NULL, logreg = FALSE, k = 10, ridge = 1e-06 ) # S3 method for class 'data.table' fill_NA_N( x, model, posit_y, posit_x, w = NULL, logreg = FALSE, k = 10, ridge = 1e-06 ) # S3 method for class 'matrix' fill_NA_N( x, model, posit_y, posit_x, w = NULL, logreg = FALSE, k = 10, ridge = 1e-06 ) ``` -------------------------------- ### print(__) Source: https://polkas.github.io/miceFast/reference/index.html Print method specifically for pooled Multiple Imputation (MI) results. ```APIDOC ## print(__) ### Description Print method for pooled MI results. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters (Specific parameters not detailed in the source text) ### Request Example (Example not provided in the source text) ### Response (Specific response details not provided in the source text) ``` -------------------------------- ### summary.miceFast_pool Source: https://polkas.github.io/miceFast/reference/summary.miceFast_pool.html Displays the full pooling diagnostics including within- and between-imputation variance, relative increase in variance, proportion of variance due to missingness, fraction of missing information, and confidence intervals. ```APIDOC ## summary.miceFast_pool ### Description Displays the full pooling diagnostics including within- and between-imputation variance, relative increase in variance, proportion of variance due to missingness, fraction of missing information, and confidence intervals. ### Method S3 method for class 'miceFast_pool' ### Arguments * `object` (miceFast_pool) - an object of class "miceFast_pool", as returned by `pool`. * `...` - additional arguments (currently ignored). ### Value Invisibly returns the full diagnostics data.frame. ``` -------------------------------- ### print.miceFast_pool Source: https://polkas.github.io/miceFast/reference/print.miceFast_pool.html Prints a concise summary of pooled multiple imputation results, showing the key inference columns: estimate, std.error, statistic, df, and p.value. ```APIDOC ## print.miceFast_pool ### Description Prints a concise summary of pooled multiple imputation results, showing the key inference columns: estimate, std.error, statistic, df, and p.value. ### Method Signature ```R print(x, ...) ``` ### Arguments * **x** (miceFast_pool) - An object of class "miceFast_pool", as returned by `pool`. * **...** - Additional arguments (currently ignored). ### Value Invisibly returns `x`. ``` -------------------------------- ### Error Handling for Small Groups in Imputation Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Shows how to wrap `fill_NA()` calls in `tryCatch()` to handle potential errors when imputing data for small groups that may lack sufficient observations. ```R tryCatch( fill_NA(x = ., model = "lda", posit_y = "y", posit_x = c("x1", "x2")), error = function(e) .[["y"]] ) ``` -------------------------------- ### Multiple Imputation Workflow with pool() Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Perform a full multiple imputation workflow by generating multiple completed datasets, fitting a model on each, and then pooling the results using Rubin's rules with the `pool()` function. This method is suitable for any model with `coef()` and `vcov()` methods. ```R data(air_miss) # Select the 4 core variables: Ozone and Solar.R have NAs; Wind and Temp are complete. df <- air_miss[, c("Ozone", "Solar.R", "Wind", "Temp")] # Step 1: Generate m = 10 completed datasets. # Impute Solar.R first (predictors fully observed), then Ozone # (can now use the freshly imputed Solar.R). This sequential order # ensures all NAs are filled in a single pass. set.seed(1234) completed <- lapply(1:10, function(i) { df %>% mutate(Solar.R = fill_NA(., "lm_bayes", "Solar.R", c("Wind", "Temp"))) %>% mutate(Ozone = fill_NA(., "lm_bayes", "Ozone", c("Solar.R", "Wind", "Temp"))) }) # Step 2: Fit the analysis model on each completed dataset fits <- lapply(completed, function(d) lm(Ozone ~ Solar.R + Wind + Temp, data = d)) # Step 3: Pool using Rubin's rules pool_res <- pool(fits) pool_res ``` ```R summary(pool_res) ``` -------------------------------- ### Grouped Imputation with `naive_fill_NA` Source: https://polkas.github.io/miceFast/reference/naive_fill_NA.html Shows how to apply `naive_fill_NA` separately for each group level within a dataset. This can be useful for maintaining group-specific imputation characteristics. ```R # Could be useful to run it separately for each group level do.call(rbind, Map(naive_fill_NA, split(air_miss, air_miss$groups))) ``` -------------------------------- ### neibo function Source: https://polkas.github.io/miceFast/reference/neibo.html This function uses pre-sorting of y and binary search to find one of the k closest values for each miss. ```APIDOC ## neibo(y, miss, k) ### Description This function uses pre-sorting of y and binary search to find one of the k closest values for each miss. ### Arguments * **y** (numeric vector) - Numeric vector values to be looked up * **miss** (numeric vector) - Numeric vector values to be looked for * **k** (integer) - Integer number of nearest neighbours to sample from ### Value a numeric vector ``` -------------------------------- ### Summary of Pooled Imputed Datasets Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Displays pooled results from multiple imputed datasets using Rubin's rules. Useful for understanding the overall effect of variables after imputation. ```R summary(pool(fits)) ``` -------------------------------- ### Compare Coefficients Across Imputation Methods Source: https://polkas.github.io/miceFast/articles/missing-data-and-imputation.html Compares the estimated coefficients and confidence intervals for the 'Wind' variable across different imputation methods. Useful for evaluating the impact of imputation on results. ```R comparison <- data.frame( method = c("Complete cases", "Mean imputation", "Regression (lm_pred)", "MI (lm_bayes, m=20)"), estimate = c(coef(fit_cc)["Wind"], coef(fit_mean)["Wind"], coef(fit_pred)["Wind"], pool_s$estimate[pool_s$term == "Wind"]), ci_low = c(ci_cc["Wind", 1], ci_mean["Wind", 1], ci_pred["Wind", 1], pool_s$conf.low[pool_s$term == "Wind"]), ci_high = c(ci_cc["Wind", 2], ci_mean["Wind", 2], ci_pred["Wind", 2], pool_s$conf.high[pool_s$term == "Wind"]), n_used = c(nrow(air_miss[complete.cases(air_miss[, c("Ozone", "Wind", "Temp")]), ]), nrow(air_miss), nrow(air_miss), nrow(air_miss)) ) comparison$ci_width <- comparison$ci_high - comparison$ci_low comparison ``` -------------------------------- ### Imputation with Unsorted Groups in miceFast Source: https://polkas.github.io/miceFast/articles/miceFast-intro.html Demonstrates imputation when the grouping variable is not pre-sorted. The data is automatically sorted upon the first imputation, and `get_index()` is used to retrieve the original order. ```R data <- cbind(as.matrix(airquality[, -5]), intercept = 1, index = 1:nrow(airquality)) weights <- rgamma(nrow(data), 3, 3) groups <- as.numeric(sample(1:8, nrow(data), replace = TRUE)) model <- new(miceFast) model$set_data(data) model$set_w(weights) model$set_g(groups) model$update_var(1, model$impute("lm_pred", 1, 6)$imputations) model$update_var(2, model$impute_N("lm_bayes", 2, c(1, 3, 4, 5, 6), 10)$imputations) head(cbind(model$get_data(), model$get_g(), model$get_w())[order(model$get_index()), ], 4) ``` ```R ## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] ## [1,] 41 190 7.4 67 1 1 1 6 0.6627979 ## [2,] 36 118 8.0 72 2 1 2 8 1.1256717 ## [3,] 12 149 12.6 74 3 1 3 2 0.6791476 ## [4,] 18 313 11.5 62 4 1 4 3 0.2004544 ``` -------------------------------- ### neibo() Source: https://polkas.github.io/miceFast/reference/index.html Identifies one of the k closest points in a given vector for each value in a second vector, chosen randomly. ```APIDOC ## neibo() ### Description Finding in random manner one of the k closest points in a certain vector for each value in a second vector. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters (Specific parameters not detailed in the source text) ### Request Example (Example not provided in the source text) ### Response (Specific response details not provided in the source text) ``` -------------------------------- ### pool() Source: https://polkas.github.io/miceFast/reference/index.html Pools results from statistical models that have been fitted on multiply imputed datasets. ```APIDOC ## pool() ### Description Pool results from models fitted on multiply imputed datasets. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters (Specific parameters not detailed in the source text) ### Request Example (Example not provided in the source text) ### Response (Specific response details not provided in the source text) ``` -------------------------------- ### naive_fill_NA() Source: https://polkas.github.io/miceFast/reference/index.html Provides a simple and automatic method for imputing missing values. ```APIDOC ## naive_fill_NA() ### Description `naive_fill_NA` function for the simple and automatic imputation. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters (Specific parameters not detailed in the source text) ### Request Example (Example not provided in the source text) ### Response (Specific response details not provided in the source text) ```