SLIDE 10 # simple , single imputation is.na(x) x[is.na(x)] x[is.na(x)] <- mean(x, na.rm = TRUE) # extracting complete cases d <- data.frame(a = 1:4, b = c(1,2,NA ,4), c = c(1,NA ,3 ,4)) complete.cases(d) d[complete.cases(d), ]
2.3 Matrix multiplication
This is the dot product we saw earlier with vectors generalized to work for matrices. Matrices are conformable (i.e., can be multiplied) if they are m-by-n and n-by-p. So number of columns of the first matrix must match number of rows of the second matrix. Otherwise, non-conformable. The output matrix from matrix multiplication is an m-by-p matrix.
# inner product (or dot product) of two vectors 1:3 %*% 2:4 1*2 + 2*3 + 3*4 # dot product
works for conformable vectors or matrices! 1:3 %*% 1:2 mm <- function(A,B){ m <- nrow(A) n <- ncol(B) C <- matrix(NA ,nrow=m,ncol=n) for(i in 1:m) { for(j in 1:n) { C[i,j] <- paste(’(’,A[i,],’*’,B[,j],’)’,sep=’’,collapse =’+’) } } print(C, quote=FALSE) } # conformability A <- matrix (1:6, nrow = 3) B <- matrix (2:5, nrow = 2) A %*% B B %*% A # non -conformable mm(A,B) # dimension of output A <- matrix (1:30 , ncol = 3) B <- matrix (1:3, nrow = 3) A %*% B mm(A,B)
10