Calculating R matrix in QR decomposition with column pivoting in R

1.4k views Asked by At

I have a matrix A which can get by following code:

        b = matrix(c(20, 33, 10, 12, 14, 22, 34, 55, 11, 40, 0, 0, 0, 0, 0, 33,40, 66, 
                  78, 90, 11, 45, 32, 55, 65), nrow = 5, ncol= 5) 

        A =crossprod(b)
        > A
           [,1]  [,2] [,3]  [,4]  [,5]
       [1,] 1929  2804    0  4836  3595
       [2,] 2804  6386    0 10174  6737
       [3,]    0     0    0     0     0
       [4,] 4836 10174    0 21229 14415
       [5,] 3595  6737    0 14415 10420

I want to apply qr decomposition with column pivoting for matrix A, then I do the following code to get matrix R, but we know that t(R)%*%Rshould be the same as matrix A, why they are not samea according to order of row or column? How can I get the correct matrix of R?

       qr.decom = qr(-b, 1e-20)

       > qr.decom
        $qr
             [,1]        [,2]        [,3]        [,4] [,5]
      [1,] 43.9203825  63.8427955 110.1083307  81.8526569    0
      [2,]  0.7513596 -48.0634732 -65.4213304 -31.4437859    0
      [3,]  0.2276847  -0.8649054 -69.4636960 -48.1581960    0
      [4,]  0.2732217   0.1064337  -0.8613864  20.3031782    0
      [5,]  0.3187586  -0.4410522  -0.3253288   0.9490613    0

      $rank
      [1] 4

      $qraux
     [1] 1.455369 1.214671 1.390096 1.315092 0.000000

     $pivot
     [1] 1 2 4 5 3

     attr(,"class")
     [1] "qr"

     R = qr.R(qr.decom)
     > R
           [,1]      [,2]      [,3]      [,4] [,5]
     [1,] 43.92038  63.84280 110.10833  81.85266    0
     [2,]  0.00000 -48.06347 -65.42133 -31.44379    0
     [3,]  0.00000   0.00000 -69.46370 -48.15820    0
     [4,]  0.00000   0.00000   0.00000  20.30318    0
     [5,]  0.00000   0.00000   0.00000   0.00000    0

     > print(t(R)%*%R)
          [,1]  [,2]  [,3]  [,4] [,5]
     [1,] 1929  2804  4836  3595    0
     [2,] 2804  6386 10174  6737    0
     [3,] 4836 10174 21229 14415    0
     [4,] 3595  6737 14415 10420    0
     [5,]    0     0     0     0    0
1

There are 1 answers

0
tonytonov On BEST ANSWER

Rows and columns are permuted in accordance to qr.decom$pivot. Apply a reverse permutation via order:

(t(R)%*%R)[order(qr.decom$pivot), order(qr.decom$pivot)]
     [,1]  [,2] [,3]  [,4]  [,5]
[1,] 1929  2804    0  4836  3595
[2,] 2804  6386    0 10174  6737
[3,]    0     0    0     0     0
[4,] 4836 10174    0 21229 14415
[5,] 3595  6737    0 14415 10420

all.equal(crossprod(b), (t(R)%*%R)[order(qr.decom$pivot), order(qr.decom$pivot)])
[1] TRUE

Related question here.