Home > Software design >  Multiplying factor to certain cells in matrix in R
Multiplying factor to certain cells in matrix in R

Time:11-19

I have the following correlation matrix, cor.mat below. I want to multiply all numbers by 15% except the cell [1,1] [2,2] [3,3] [4,4]. Does anyone have a good code to implent this in R?

       1         2         3        4
1  1.0000000 0.1938155 0.1738809 0.2465276
2  0.1938155 1.0000000 0.4045694 0.2729958
3  0.1738809 0.4045694 1.0000000 0.3340883
4  0.2465276 0.2729958 0.3340883 1.0000000

CodePudding user response:

You can use diag which returns the diagonal of a matrix

matrix = matrix*0.15
diag(matrix) = 1

CodePudding user response:

Create a logical matrix excluding the diag and do the multiplication

i1 <- row(m1) != col(m1)
m1[i1] <- m1[i1] * 0.15
  • Related