[d79ff0]: / R / unscale.R

Download this file

43 lines (41 with data), 1.2 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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)
}