a b/R/unscale.R
1
#' Unscales a scaled data.frame
2
#'
3
#' \code{unscale} is a generic function that unscale and/or uncenter the columns
4
#' of a matrix generated by the scale base function
5
#'
6
#' @param x A numeric matrix.
7
#'
8
#' @return
9
#' Return a matrix, uncenterd and unscaled. Attributes "scaled:center" and
10
#' "scaled:scale" are removed.
11
#'
12
#'
13
#' @details
14
#' \code{unscale} uses attributes added by the scale function "scaled:scale" and
15
#' "scaled:center" and use these scaling factor to retrieve the initial matrix.
16
#' It first unscales and then uncenters.
17
#'
18
#'
19
#' @seealso \code{\link[base]{scale}}
20
#'
21
#' @examples
22
#' X <- matrix(1:9, ncol = 3)
23
#' X.scale <- scale(X, center = TRUE, scale = TRUE)
24
#' X.unscale <- unscale(X.scale)
25
#' all(X == X.unscale)
26
#'
27
#' @export
28
unscale <- function(x){
29
    stopifnot(is(x, "matrix"))
30
    attrib <- attributes(x)
31
32
    if("scaled:scale" %in% names(attrib)){
33
        x  <- x * attrib$`scaled:scale`
34
        attr(x, "scaled:scale") <- NULL
35
    }
36
    if("scaled:center" %in% names(attrib)){
37
        x <- x + matrix(rep(attrib$`scaled:center`,
38
                            each = nrow(x)), nrow = nrow(x))
39
        attr(x, "scaled:center") <- NULL
40
    }
41
    return(x)
42
}