Another decomposition method is QR decomposition. One advantage of QR decomposition over LU decomposition is that this method does not require that the decomposition be carried out on a square matrix. QR decomposition results in factoring matrix A (having independent columns) into the product of two matrices, namely Q and R: .
where Q is an orthogonal matrix1 and R is an upper-triangular matrix.
23.1 QR Decomposition using R
Although there is a way to hand-calculate the matrices Q and R (e.g., using the Gram-Schmidt process), we will rely on computation. To carry out a QR decomposition in R, we will use the qr() function which factors the matrix and returns a list of output related to the QR decomposition. To extract the actual Q and R matrices from this output, we will use the qr.Q() and qr.R() functions, respectively.
# Create matrix AA =matrix(data =c(5, -4, 1, 2), nrow =2 )# Carry out QR decompositionqr_decomp =qr(A)# View Q matrixqr.Q(qr_decomp)
You can see that R is an upper-triangular matrix, and we can check that Q is orthonormal by testing whether \(\mathbf{Q}^{\intercal} = \mathbf{Q}^{-1}\).
Since R is an upper-triangular matrix, we can use back substitution to solve for the elements of b. Using the same simulated data as the example from last chapter, consider the following simulated data set of \(n=50\) cases:
# Number of casesn =50# Create 50 x-values evenly spread b/w 1 and 500 x =seq(from =1, to =500, len = n)# Create X matrixX =cbind(1, x, x^2, x^3)colnames(X) <-c("Intercept", "x", "x2", "x3")# Create b matrixb =matrix(data =c(1, 1, 1, 1), nrow =4 )# Create vector of y-valuesset.seed(1)y = X %*% b +rnorm(n, mean =0, sd =1)
We can use QR decomposition to solve for b.
# Carry out QR decompositionQR =qr(X)# Solve for bbacksolve(qr.R(QR), t(qr.Q(QR)) %*% y)
QR decomposition is how the lm() function computes the regression coefficients.
The columns of an orthogonal matrix are orthogonal unit vectors and it has the property that \(\mathbf{Q}^{T}\mathbf{Q}=\mathbf{I}\) or that \(\mathbf{Q}^{\intercal} = \mathbf{Q}^{-1}\).↩︎