samedi 1 août 2020

Randomize and compare matrices in R

I have two matrices (1 and 2) which I multiply, resulting in the concordance matrix (c).

I need to randomize one of theses matrices 1000 times and them compare the number of times the value of these concordance matrices were higher than the first comparation.

# Exemple:
 mat1 <- matrix(rbinom(222, 1, 0.5),nrow=74,ncol=3) # habitat

 mat2 <- matrix(rbinom(592, 1, 0.5),nrow=74,ncol=8) # modular

 tmat1 <- t(mat1)

 # Multipying the tranposed matrix 1 by matrix 2:

 c <- tmat1%*%mat2 # concordance matrix c

 resu <- matrix(NA,nrow=3,ncol=8) # creating the matrix to fill with the results of values higher than c

  for(r in 1:1000) {

mat3 <- apply(mat1,1,sample) # randomizing matrix 1, maintaining the number of intercations by nodes

cc <- mat3%*%mat2 # multiplying these matrices 

for (i in 1:dim(c)[1]){ # rows

 for(j in 1:dim(c)[2]){ # columns

   if(cc[i]>=c[j]){ #  

   resu[i,j] <- sum(cc[i]>=c[j]) # filling the matrix with the number of times cc was higher then c

   } 

 }

}

}

But the result is wrong: it is resulting in a matrix with correct number of rows (3) and columns (8) but all fill out by 1.

Each element has to be a different number of times the concordance was higher in cc[i] than c[j].

Any thoughts, please?




Aucun commentaire:

Enregistrer un commentaire