[R] how to skip a specific value when using apply() function to a matrix?
Shuhua Zhan
szhan at uoguelph.ca
Fri Jul 16 05:08:34 CEST 2010
Hello R experts,
I'd like to studentize a matrix (tmp1) by column using apply() function and skip some specific values such as zeros in the example below to tmp2 but not tmp3. I used the script below and only can get a matrix tmp3. Could you please help me to studentize the matrix (tmp1) without changing the zeros and generate a new matrix tmp2?
Thanks,
Joshua
tmp1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 15 7 9 49 60 3 2 0
[2,] 13 7 10 56 21 4 3 0
[3,] 10 2 12 50 19 1 0 2
[4,] 15 5 30 52 120 2 4 0
[5,] 12 9 71 76 211 4 3 1
[6,] 11 12 2 69 18 5 2 0
tmp2
[1,] 1.1296201 0.0000000 -0.5207910 -0.8630035 -0.1913482 -0.1132277 -0.9561829 0.0000000
[2,] 0.1613743 0.0000000 -0.4817316 -0.2380699 -0.6944435 0.5661385 0.2390457 0.0000000
[3,] -1.2909944 -1.4680505 -0.4036130 -0.7737273 -0.7202433 -1.4719601 0.0000000 0.7071068
[4,] 1.1296201 -0.5872202 0.2994548 -0.5951748 0.5826446 -0.7925939 1.4342743 0.0000000
[5,] -0.3227486 0.5872202 1.9008870 1.5474546 1.7565336 0.5661385 0.2390457 -0.7071068
[6,] -0.8068715 1.4680505 -0.7942062 0.9225210 -0.7331431 1.2455047 -0.9561829 0.0000000
tmp3
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1.1296201 0.0000000 -0.5207910 -0.8630035 -0.1913482 -0.1132277 -0.243975 -0.5976143
[2,] 0.1613743 0.0000000 -0.4817316 -0.2380699 -0.6944435 0.5661385 0.487950 -0.5976143
[3,] -1.2909944 -1.4680505 -0.4036130 -0.7737273 -0.7202433 -1.4719601 -1.707825 1.7928429
[4,] 1.1296201 -0.5872202 0.2994548 -0.5951748 0.5826446 -0.7925939 1.219875 -0.5976143
[5,] -0.3227486 0.5872202 1.9008870 1.5474546 1.7565336 0.5661385 0.487950 0.5976143
[6,] -0.8068715 1.4680505 -0.7942062 0.9225210 -0.7331431 1.2455047 -0.243975 -0.5976143
Here is my script:
stud<- function(x){
x<-(x-mean(x))/sd(x)
return (x)
}
tmp3<-apply(tmp1,2,stud)
More information about the R-help
mailing list