--- a +++ b/R/unscale.R @@ -0,0 +1,42 @@ +#' Unscales a scaled data.frame +#' +#' \code{unscale} is a generic function that unscale and/or uncenter the columns +#' of a matrix generated by the scale base function +#' +#' @param x A numeric matrix. +#' +#' @return +#' Return a matrix, uncenterd and unscaled. Attributes "scaled:center" and +#' "scaled:scale" are removed. +#' +#' +#' @details +#' \code{unscale} uses attributes added by the scale function "scaled:scale" and +#' "scaled:center" and use these scaling factor to retrieve the initial matrix. +#' It first unscales and then uncenters. +#' +#' +#' @seealso \code{\link[base]{scale}} +#' +#' @examples +#' X <- matrix(1:9, ncol = 3) +#' X.scale <- scale(X, center = TRUE, scale = TRUE) +#' X.unscale <- unscale(X.scale) +#' all(X == X.unscale) +#' +#' @export +unscale <- function(x){ + stopifnot(is(x, "matrix")) + attrib <- attributes(x) + + if("scaled:scale" %in% names(attrib)){ + x <- x * attrib$`scaled:scale` + attr(x, "scaled:scale") <- NULL + } + if("scaled:center" %in% names(attrib)){ + x <- x + matrix(rep(attrib$`scaled:center`, + each = nrow(x)), nrow = nrow(x)) + attr(x, "scaled:center") <- NULL + } + return(x) +}