# a) # setwd("...") help(c) help(matrix) # b) a <- matrix(c(2, 1, 5, -2, 7, 0, 5, -8, -1), ncol = 3, byrow = TRUE) x1 <- c(8, -4, 2) x2 <- matrix(c(8, -4, 2), nrow = 1) b <- c(3, 10, -19) y1 <- x1 %*% solve(a) + b y2 <- x2 %*% solve(a) + b y3 <- solve(a) %*% x1 + b # Note that R does not give an error here y4 <- solve(a) %*% x2 + b # Here, R gives an error # Note that when multiplying vectors and matrices, the safe way # is to always use variables of the class matrix # c) set.seed(123) # install.packages("mvtnorm") # Run this only once library(mvtnorm) n <- 100 mu <- c(3, 1) sigma <- matrix(c(4, 1, 1, 2), byrow = TRUE, ncol = 2) x <- rmvnorm(n, mu, sigma) plot(x) # d) mx <- apply(x, 2, mean) colMeans(x) sx <- cov(x) sum(diag(sx)) - sum(eigen(sx)$values) prod(eigen(sx)$values) - det(sx) # e) b <- c(3, 1) a <- matrix(c(1, 2, 3, 1), byrow = TRUE, ncol = 2) y <- sweep(x %*% t(a), 2, b, "+") # another way ones <- rep(1, n) y2 <- x %*% t(a) + ones %*% t(b) # When comparing if multivariate expressions are the same, # use, e.g., the Frobenius norm norm(colMeans(y) - a %*% colMeans(x) - b, type = "F") norm(cov(y) - a %*% cov(x) %*% t(a), type = "F") # f) # Here, we make a conversion to type matrix, # note that many of the basic matrix operations are not # available for variables of type data.frame d <- as.matrix(read.table("data/data.txt", sep = "\t", header = FALSE)) pairs(d) center <- function(x) { ave <- apply(x, 2, mean) sweep(x, 2, ave, "-") } cent <- center(d) apply(cent, 2, mean) cov(cent) cor(cent) eigen(cov(cent))$values eigen(cor(cent))$values eigen(cov(cent))$vectors eigen(cor(cent))$vectors