R/unscale.R

Defines functions unscale_dt

#' @title Reverse a scale
#' @description
#' Computes x = sz+c, which is the inverse of z = (x - c)/s
#' provided by the \code{scale} function.
#' @param z a numeric matrix(like) object
#' @param center either NULL or a numeric vector of length equal to the number of columns of z
#' @param scale  either NULL or a a numeric vector of length equal to the number of columns of z
#' @usage unscale_dt (matrix)
#' @return data frame or matrix
#' @export
#' @seealso \code{\link{scale}}
#'  mtcs <- scale(mtcars)
#'
#'  all.equal(
#'    unscale_dt(mtcs),
#'    as.matrix(mtcars),
#'    check.attributes=FALSE
#'  )

unscale_dt <- function(z, center = attr(z, "scaled:center"), scale = attr(z, "scaled:scale")) {
  if(!is.null(scale))  z <- sweep(z, 2, scale, `*`)
  if(!is.null(center)) z <- sweep(z, 2, center, `+`)
  structure(z,
            "scaled:center"   = NULL,
            "scaled:scale"    = NULL,
            "unscaled:center" = center,
            "unscaled:scale"  = scale
  )
}
St-Digital-Twin/Dtwin documentation built on Jan. 1, 2022, 8:11 p.m.