R/z_trans.R

#' z-Transformation
#'
#' Scale data by it's mean and standard deviation.
#' This function is almost equivalent to \link{scale}, but it does not set any attributes and
#' returns a simple \code{vector}, so it should be easier to use within \code{dplyr}-workflows.
#'
#' @param x A \code{vector} with numeric data.
#' @param na.rm If \code{TRUE}, missing values (\code{NA}) will be ignored.
#'
#' @return A \code{vector} of the same length as the input of type \code{numeric}.
#' @export
#' @examples
#' \dontrun{
#' x <- c(1, 2, 6, 2, 1, 5, 7, 8, 4, 3, 2, 2, 2)
#' z_trans(x)
#' }

z_trans <- function(x, na.rm = FALSE){
  if (!is.numeric(x)) {
    stop("Expecting numeric input.")
  }
  if (na.rm) {
    x <- x[!is.na(x)]
  }

  x_z <- ((x - mean(x, na.rm = na.rm)) / sd(x, na.rm = na.rm))
  return(x_z)
}
jemus42/qmtut documentation built on May 19, 2019, 4:03 a.m.