[R] Scaling data

(Ted Harding) Ted.Harding at manchester.ac.uk
Mon Sep 28 12:11:26 CEST 2009


On 28-Sep-09 09:55:04, Dry, Jonathan R wrote:
> Hello all
> I have a data frame representing a matrix of data.  For each of my
> variables (rows) I want to scale the data between 0 (representing
> the minimum value in that row) and 1 (representing the maximum value
> in that row).  I was wondering if there is a simple function anywhere
> that does this?
> Jonathan

Example:
set.seed(12345)
X <- matrix(rnorm(50),ncol=5)
X
#            [,1]       [,2]       [,3]        [,4]       [,5]
# [1,]  0.5855288 -0.1162478  0.7796219  0.81187318  1.1285108
# [2,]  0.7094660  1.8173120  1.4557851  2.19683355 -2.3803581
# [3,] -0.1093033  0.3706279 -0.6443284  2.04919034 -1.0602656
# [4,] -0.4534972  0.5202165 -1.5531374  1.63244564  0.9371405
# [5,]  0.6058875 -0.7505320 -1.5977095  0.25427119  0.8544517
# [6,] -1.8179560  0.8168998  1.8050975  0.49118828  1.4607294
# [7,]  0.6300986 -0.8863575 -0.4816474 -0.32408658 -1.4130988
# [8,] -0.2761841 -0.3315776  0.6203798 -1.66205024  0.5674033
# [9,] -0.2841597  1.1207127  0.6121235  1.76773385  0.5831877
#[10,] -0.9193220  0.2987237 -0.1623110  0.02580105 -1.3067988

 t(apply(X,1,function(x){(x-min(x))/(max(x)-min(x))}))
#           [,1]      [,2]      [,3]      [,4]      [,5]
# [1,] 0.5637853 0.0000000 0.7197136 0.7456233 1.0000000
# [2,] 0.6750480 0.9170842 0.8380998 1.0000000 0.0000000
# [3,] 0.3058291 0.4601749 0.1337652 1.0000000 0.0000000
# [4,] 0.3451928 0.6508554 0.0000000 1.0000000 0.7817338
# [5,] 0.8986346 0.3454820 0.0000000 0.7552443 1.0000000
# [6,] 0.0000000 0.7272473 1.0000000 0.6373475 0.9049509
# [7,] 1.0000000 0.2578024 0.4558793 0.5329941 0.0000000
# [8,] 0.6071889 0.5829194 1.0000000 0.0000000 0.9767894
# [9,] 0.0000000 0.6846712 0.4368079 1.0000000 0.4227058
#[10,] 0.2413400 1.0000000 0.7128445 0.8300101 0.0000000

with identical results if applied to Y <- as.data.frame(X)

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 28-Sep-09                                       Time: 11:11:23
------------------------------ XFMail ------------------------------




More information about the R-help mailing list