Home > other >  How to get original value after applying scale()?
How to get original value after applying scale()?

Time:06-16

How can you get the original values after applying scale() to a vector?

x <- c(11, 12, 13,24, 25, 16, 17, 18, 19)

scaled <- scale(x)

CodePudding user response:

You may use attributes

x <- c(11, 12, 13,24, 25, 16, 17, 18, 19)

y <- scale(x)
z <- attributes(y)
    
y * (z$'scaled:scale')   z$'scaled:center'

CodePudding user response:

You could also use the unscale function from the DMwR package:

remotes::install_github("cran/DMwR")
library(DMwR)
x <- c(11, 12, 13,24, 25, 16, 17, 18, 19)
scaled <- scale(x)
original <- unscale(scaled, scaled)

Output:

      [,1]
 [1,]   11
 [2,]   12
 [3,]   13
 [4,]   24
 [5,]   25
 [6,]   16
 [7,]   17
 [8,]   18
 [9,]   19

CodePudding user response:

Another way to do it, calculate the mean and SD of x beforehand

x <- c(11, 12, 13,24, 25, 16, 17, 18, 19)

scaled <- scale(x)
m <- mean(x)
sd <- sd(x)
unscaled <- scaled*sd   m 

CodePudding user response:

You could also use the attributes from scaled within the scale function itself:

x <- c(11, 12, 13,24, 25, 16, 17, 18, 19)

scaled <- scale(x)

x <- scale(scaled,
           center = -attr(scaled,"scaled:center")/attr(scaled,"scaled:scale"),
           scale = 1/attr(scaled,"scaled:scale")
           )

x

Output:

> x
      [,1]
 [1,]   11
 [2,]   12
 [3,]   13
 [4,]   24
 [5,]   25
 [6,]   16
 [7,]   17
 [8,]   18
 [9,]   19
attr(,"scaled:center")
[1] -3.483366
attr(,"scaled:scale")
[1] 0.20226

CodePudding user response:

Try

as.numeric(scaled) * attr(scaled , "scaled:scale") 
                     attr(scaled , "scaled:center")
  • Related