# This is a file of R commands illustrating basic matrix operations. # # Read in Theil's data together with row and column labels. yx <- read.table("matrixalg.data") # Read in the data frame # Attach database xy to the R search path so objects in xy can # be accessed by name. attach(yx) # Divert output from console to file matrixalR.out # sink("matrixalg.Rout") yx # print yx y <- as.matrix(yx[,1]) # Copy first column of yx to vextor y y x <- as.matrix(yx[,2:3]) # Copy remaining columns of yx to matrix x x n <- nrow(x) # Number of rows in maxtrix x n x <- cbind(1, x) # Create nx3 design matrix by concatenation x y2 <- y^2 # Square the elements of y y2 y2sum <- sum(y2) # Sum the elements of y2 y2sum ynorm <- sqrt(y2sum) # Calculate the norm or length of y ynorm u <- as.matrix(x[,2]) # Copy the second column of x to vector u u unorm <- sqrt(sum(u^2)) # Calculte the norm of u in one step unorm z <- as.matrix(x[,1] + x[,2]) # Add the first two columns of x z w <- as.matrix(2*x[,1]) # Scalar multiplication of a vector w ip <- t(y) %*% u # Calculte the innner or dot product of y and u ip cosyu <- ip/(ynorm*unorm) # Calculate the cosine of the angle between y and u cosyu angleyu <- acos(cosyu) # Angle between y and u in degrees angleyu rankx = qr(x)$rank # Compute rank of x by qr decomposition rankx singvalx <- svd(x)$d # Check rank by counting nonzero singular values singvalx xtx <- t(x) %*% x # Multiply x' by x xtx detxtx <- det(xtx) # Calculate determinant of xtx detxtx xtxi <- solve(xtx) # Get inverse of xtx xtxi bols <- xtxi %*% t(x) %*% y # OLS estimate of regression coefficients bols resid <- y - x %*% bols # OLS residuals resid xr <- t(x) %*% resid # Check orthogonality of regressors and residuals xr #sink() #End diversion of output to file q() # Quit R