Search code examples
rdataframematrixmatrix-multiplicationdiagonal

divide each row with the value in the main diagonal in R


I have a dataset in R as follows.

dat <- as.data.frame(t(cbind(c(5,10,15,20),c(10,20,30,40),c(50,100,150,200),c(200,400,600,800))))
    dat

How can create a new dataframe dat_new that each row has been divided by the value in the main diagonal of the corresponding row? The final results must be:

> dat_new
1  1     5     3     4 
2  0.5   1     1.5   2 
3  0.33  0.66  1     1.33
4  0.25  0.5   0.75  1

Solution

  • We extract the diag as a vector and divide

    dat/diag(as.matrix(dat))
    

    -output

         V1        V2   V3       V4
    1 1.0000000 2.0000000 3.00 4.000000
    2 0.5000000 1.0000000 1.50 2.000000
    3 0.3333333 0.6666667 1.00 1.333333
    4 0.2500000 0.5000000 0.75 1.000000