An Eager Avocado

Eager Avocado

I give myself very good advice, but I very seldom follow it.

apply() function

,

Data

This is the value of matrix a

##   [,1] [,2] [,3]
## A    1    6   11
## B    2    7   12
## C    3    8   13
## D    4    9   14
## E    5   10   15

The mean of a’s rows

apply(a,1, mean)
##  A  B  C  D  E 
##  6  7  8  9 10

The stddev of a’s rows

apply(a,1, sd)
## A B C D E 
## 5 5 5 5 5

z-score conversion

z0 function is defined to normalize a vector against its own mean and stddev

z0= function(x) {return((x-mean(x)) / sd(x))}

z1 function is defined to normalize a vector against another mean and stddev

z1= function(x) {return((x-xm)/xs )}

Applying z0() along the rows of a gives

apply(a,1,z0)
##       A  B  C  D  E
## [1,] -1 -1 -1 -1 -1
## [2,]  0  0  0  0  0
## [3,]  1  1  1  1  1
apply(t(a), 2, z0)
##       A  B  C  D  E
## [1,] -1 -1 -1 -1 -1
## [2,]  0  0  0  0  0
## [3,]  1  1  1  1  1

Applying z0() along the columns of a gives

apply(a,2,z0)
##         [,1]       [,2]       [,3]
## A -1.2649111 -1.2649111 -1.2649111
## B -0.6324555 -0.6324555 -0.6324555
## C  0.0000000  0.0000000  0.0000000
## D  0.6324555  0.6324555  0.6324555
## E  1.2649111  1.2649111  1.2649111

The result of apply() along the row (axis=1) of the matrix is transposed since each operation return a column vector, and these vectors are cbind to give the final matrix.

Applying z1() with precalculated mean and sd gives

xm = c(6,7,8,9,10)
xs = c(5,5,5,5,5)
apply(a,2,z1)
##   [,1] [,2] [,3]
## A   -1    0    1
## B   -1    0    1
## C   -1    0    1
## D   -1    0    1
## E   -1    0    1
apply(t(a),2,z1)
## Warning in x - xm: longer object length is not a multiple of shorter
## object length
## Warning in x - xm: longer object length is not a multiple of shorter
## object length
## Warning in x - xm: longer object length is not a multiple of shorter
## object length
## Warning in x - xm: longer object length is not a multiple of shorter
## object length
## Warning in x - xm: longer object length is not a multiple of shorter
## object length
##         A    B    C    D    E
## [1,] -1.0 -0.8 -0.6 -0.4 -0.2
## [2,] -0.2  0.0  0.2  0.4  0.6
## [3,]  0.6  0.8  1.0  1.2  1.4
## [4,] -1.6 -1.4 -1.2 -1.0 -0.8
## [5,] -0.8 -0.6 -0.4 -0.2  0.0