R/mode_imputation.R

#' Mode Imputation
#'
#' Perfom mode imputation of factor and numeric variables
#'
#' @export
#'
#' @author David Navega
#'
#' @param x a data.frame with missing values
#'
mode_imputation <- function(x) {

  # initialize and assess class of each variable
  x_names <- colnames(x)
  x_class <- lapply(x, class)
  x_class <- named_apply(x_class, numeric_factor_class, simplify = TRUE)

  # compute mode ----
  x_mode <- named_apply(x_names, function(current) {

    current_x <- x[[current]]

    switch(x_class[current],

      factor = {
        factor_mode(x = current_x)
      },

      numeric = {
        numeric_mode(x = current_x)
      }

    )

  })

  # mode imputation ----
  x_imputed <- named_apply(x_names, function(current) {

    current_x <- x[[current]]
    is_missing <- is.na(current_x)
    current_x[is_missing] <- x_mode[[current]]

    return(current_x)

  })
  x_imputed <- as.data.frame(x_imputed)

  # return ----
  rout <- x_imputed
  return(rout)

}
dsnavega/imputeForest documentation built on May 8, 2019, 2:43 p.m.