Search code examples
rdataframenormalize

Convert data back from normalized values


I have used scale to normalize the data. Example data is show below

structure(list(pp.pmhouravg = c(106.8181818182, 114.0833333333, 
100.8333333333, 105, 102.4166666667, 117.8333333333), cc.cmhouravg = c(91.7272727273, 
86.4166666667, 82.75, 84, 59.5833333333, 41.3333333333), ss.sdhouravg = c(49.2727272727, 
46.8333333333, 47.5, 48.3333333333, 41, 45.5833333333), nn.ndhouravg = c(41.2727272727, 
45.25, 34.0833333333, 27.75, 33.0833333333, 35.3333333333)), .Names = c("pp.pmhouravg", 
"cc.cmhouravg", "ss.sdhouravg", "nn.ndhouravg"), row.names = c(NA, 
6L), class = "data.frame")

and to normalize it I used

scale(df, center = T, scale = T)

I got the following normalized data:

pp.pmhouravg cc.cmhouravg ss.sdhouravg nn.ndhouravg
1   -0.1504657    0.8893812    0.9702219    0.8259116
2    0.9290599    0.6183329    0.1404438    1.4645030
3   -1.0397516    0.4311897    0.3672155   -0.3284185
4   -0.4206285    0.4949885    0.6506801   -1.3452993
5   -0.8044848   -0.7512149   -1.8438082   -0.4889786
6    1.4862706   -1.6826775   -0.2847531   -0.1277183
attr(,"scaled:center")
pp.pmhouravg cc.cmhouravg ss.sdhouravg nn.ndhouravg 
   107.83081     74.30177     46.42045     36.12879 
attr(,"scaled:scale")
pp.pmhouravg cc.cmhouravg ss.sdhouravg nn.ndhouravg 
    6.729949    19.592842     2.939815     6.228196 

How can I convert data back after normalization.


Solution

  • Let x be your original data (may be a data frame or a matrix) and sx be the scaled one (must be a matrix, as scale returns a matrix), you can do:

    b <- attr(sx, "scaled:scale")
    a <- attr(sx, "scaled:center")
    rx <- sx * rep(b, each = nrow(sx)) + rep(a, each = nrow(sx))
    

    The "de-scaled" data rx is of course also a matrix as sx is a matrix. You can make it a data frame by simply doing:

    data.frame(rx)