In R programming, a matrix can be scaled and centred using scale()
function. But, there is no in-built function to transform the scaled matrix back to the original matrix. In this article, we’ll learn to transform the scaled matrix back to the original matrix using some simple computations.
Using Matrix Attributes
Attributes of the scaled matrix can be used to unscale the matrix back to its original matrix.
# Create matrix mt <- matrix ( c (1:20), ncol = 5) # Print original matrix cat ( "Original matrix:\n" ) print (mt) # Scale the matrix scaled.mt <- scale (mt) # Print Scaled matrix cat ( "Scaled matrix:\n" ) print (scaled.mt) # Unscale the matrix unscaled.mt <- t ( apply (scaled.mt, 1, function (r) r * attr (scaled.mt, 'scaled:scale' ) + attr (scaled.mt, 'scaled:center' ))) # Print Unscaled matrix cat ( "Unscaled matrix:\n" ) print (unscaled.mt) |
Output:
Original matrix: [, 1] [, 2] [, 3] [, 4] [, 5] [1, ] 1 5 9 13 17 [2, ] 2 6 10 14 18 [3, ] 3 7 11 15 19 [4, ] 4 8 12 16 20 Scaled matrix: [, 1] [, 2] [, 3] [, 4] [, 5] [1, ] -1.1618950 -1.1618950 -1.1618950 -1.1618950 -1.1618950 [2, ] -0.3872983 -0.3872983 -0.3872983 -0.3872983 -0.3872983 [3, ] 0.3872983 0.3872983 0.3872983 0.3872983 0.3872983 [4, ] 1.1618950 1.1618950 1.1618950 1.1618950 1.1618950 attr(, "scaled:center") [1] 2.5 6.5 10.5 14.5 18.5 attr(, "scaled:scale") [1] 1.290994 1.290994 1.290994 1.290994 1.290994 Unscaled matrix: [, 1] [, 2] [, 3] [, 4] [, 5] [1, ] 1 5 9 13 17 [2, ] 2 6 10 14 18 [3, ] 3 7 11 15 19 [4, ] 4 8 12 16 20
Using Mean and Standard Deviation
In this example, we’ll unscale the scaled matrix using mean and standard deviation of the original matrix.
# Create matrix a <- rnorm (5, 5, 2) b <- rnorm (5, 7, 5) mt <- cbind (a, b) # get center and scaling values m <- apply (df, 2, mean) s <- apply (df, 2, sd) # Print original matrix cat ( "Original matrix:\n" ) print (mt) # Scale the matrix scaled.mt <- scale (mt, center = m, scale = s) # Print Scaled matrix cat ( "Scaled matrix:\n" ) print (scaled.mt) # Unscale the matrix unscaled.mt <- t (( t (scaled.mt) * s) + m) # Print Unscaled matrix cat ( "Unscaled matrix:\n" ) print (unscaled.mt) |
Output:
Original matrix: a b [1, ] 5.552301 1.9865159 [2, ] 3.936486 17.5327829 [3, ] 5.379720 15.0981877 [4, ] 3.546333 0.5230305 [5, ] 5.043194 2.0930855 Scaled matrix: a b [1, ] 0.01543556 -2.062174 [2, ] -0.69057233 5.252016 [3, ] -0.05997146 4.106591 [4, ] -0.86104456 -2.750713 [5, ] -0.20701146 -2.012036 attr(, "scaled:center") a b 5.516974 6.369655 attr(, "scaled:scale") a b 2.288663 2.125494 Unscaled matrix: a b [1, ] 5.552301 1.9865159 [2, ] 3.936486 17.5327829 [3, ] 5.379720 15.0981877 [4, ] 3.546333 0.5230305 [5, ] 5.043194 2.0930855 attr(, "scaled:center") a b 5.516974 6.369655 attr(, "scaled:scale") a b 2.288663 2.125494
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.