Skip to content
Prev 228226 / 398500 Next

Problem with command apply

I try to utilize some operations on rows in a matrix using command 'apply'
but find a problem.

First I write a simple function to normalize a vector (ignore error
handling) as follows:
normalize = function( v ) {
	return( ( v-min(v) ) / ( max(v) - min(v) ) )
}

The function works fine for a vector:
[1] 0.00 0.25 0.50 0.75 1.00

Then I generate a matrix:
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    4    6    8   10
[3,]    3    6    9   12   15
[4,]    4    8   12   16   20
[5,]    5   10   15   20   25

The function works fine upon the columns:
[,1] [,2] [,3] [,4] [,5]
[1,] 0.00 0.00 0.00 0.00 0.00
[2,] 0.25 0.25 0.25 0.25 0.25
[3,] 0.50 0.50 0.50 0.50 0.50
[4,] 0.75 0.75 0.75 0.75 0.75
[5,] 1.00 1.00 1.00 1.00 1.00

BUT it does not work upon the rows:
[,1] [,2] [,3] [,4] [,5]
[1,] 0.00 0.00 0.00 0.00 0.00
[2,] 0.25 0.25 0.25 0.25 0.25
[3,] 0.50 0.50 0.50 0.50 0.50
[4,] 0.75 0.75 0.75 0.75 0.75
[5,] 1.00 1.00 1.00 1.00 1.00

Can anyone help me to solve this problem? Thanks in advance!