#' Replace missing values with a constant
#'
#' @param x a vector.
#' @param value scalar used as a replacement value.
#' @param trim the fraction (0 to 0.5) of observations to be
#' trimmed from each end of x before the mean is
#' computed. Values of trim outside that range
#' are taken as the nearest endpoint. See
#' \code{\link{mean}}.
#'
#' @examples
#'
#' x <- c(NA, 1, 2, NA, 4, NA, NA, 7, NA)
#' na_mean(x)
#' na_median(x)
#' na_mode( c(2, 1, 2, NA, 4, NA, NA, 3, 2, 1, NA) )
#' na_mode( c( NA, "a", NA, "b", "a", NA, NA) )
#'
#' @importFrom stats median
#'
#' @export
na_const <- function(x, value = mean(x, na.rm = TRUE)) {
if ( length(value) > 1L )
message("value has length > 1 and only the first element will be used")
nas <- is.na(x)
x <- as_imputed(x)
x[nas] <- value[1L]
x
}
#' @rdname na_const
#' @export
na_mean <- function(x, trim = 0) {
na_const(x, value = mean(x, trim = trim, na.rm = TRUE))
}
#' @rdname na_const
#' @export
na_median <- function(x) {
na_const(x, value = median(x, na.rm = TRUE))
}
#' @rdname na_const
#' @export
na_mode <- function(x) {
na_const(x, value = Mode(x, na.rm = TRUE))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.