yellowDuck
yellowDuck

Reputation: 59

How to get original value after applying scale()?

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)

Upvotes: 4

Views: 676

Answers (5)

Mohamed Desouky
Mohamed Desouky

Reputation: 4425

Try

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

Upvotes: 0

harre
harre

Reputation: 7287

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

Upvotes: 0

UseR10085
UseR10085

Reputation: 8176

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 

Upvotes: 1

Quinten
Quinten

Reputation: 41285

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

Upvotes: 1

Kra.P
Kra.P

Reputation: 15123

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'

Upvotes: 3

Related Questions