#' Median absolute deviation
#'
#' Computes the median absolute deviation.
#'
#'
#' @param scale A scaling factor; defaults to 1.482602
#' @param .f The centering function
#' @param ... Additional arguments passed to `.f`
#'
#' @export
#' @seealso [stats::mad()]
#' @examples
#' ## standard implementation
#' mads(iris[,1])
#' mads(iris[1:2])
#' mads(iris[1:2], scale = 1)
#'
#' mads(iris$Sepal.Width, mean, na.rm = TRUE) %>% head()
#' mads(iris$Sepal.Width, function(x) mean(x / 2)^3) %>% head() ## for demonstration
mads <- function(x, scale = 1.482602, .f = median, ...) {
UseMethod("mads", x)
}
#' @export
mads.default <- function(x, .f = median, ..., scale = 1.4826) {
(x - .f(x)) / abs_dev(x, .f = .f, ..., scale = scale)
}
#' @export
mads.data.frame <- function(x, .f = median, ..., scale = 1.4826) {
lapply(x, mads, .f = .f, ..., scale = scale, USE.NAMES = FALSE)
}
#' @rdname mads
#' @export
abs_dev <- function (x, .f = median, ..., scale = 1.4826) {
.f(abs(x - .f(x, ...)), ...) * scale
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.