I have calculated this hc index for every 24 values of a 24x24 square matrix (a). It returns a vector (hc) with 24 values.
hc<-vector("numeric",24L)
for (i in 1:24) {
hc[i]<- -sum((c(a[,i])/colSums(a)[i])*log((c(a[,i])/colSums(a)[i]), base = 2))
}
I want to calculate this for each of the 1000 matrices of an array and don't know exactly how to proceed (a function?, another nested "for" statement?...). And get 1000, 24length vectors. One for each matrix in the array. I would really appreciate any help. Thanks!
Here's an alternative approach, if you actually have an array:
If your matrices are in a list:
Created on 2018-03-05 by the reprex package (v0.2.0).
Firstly, your code is very inefficient. You are calculating sum of every column in the matrix twice in every iteration. It would be better to calculate all of these at the beginning, or simply to calculate a sum when needed.
The following is more "R-like" code that should also be faster:
Now, to apply this to all 1000 matrices? First, make a list of 1000 matrices:
Then, apply a function over each of these matrices: