Matrices & Arrays
10.1 Matrices (2-D, single type)
m <- matrix(1:6, nrow = 2, ncol = 3) # filled column-wise
m <- matrix(1:6, nrow = 2, byrow = TRUE) # row-wise
dim(m); nrow(m); ncol(m)
m[1, 2] # row 1, column 2
m[1, ] # first row
m[, 2] # second column
m[, 2, drop = FALSE] # keep as matrix
rownames(m) <- c("r1", "r2"); colnames(m) <- c("a", "b", "c")
m["r1", "b"]
t(m) # transpose
rbind(m, 7:9); cbind(m, d = c(0, 0))
10.2 Matrix algebra
A <- matrix(c(2, 1, 1, 3), 2)
B <- diag(2) # identity
A %*% B # matrix product
A * A # element-wise
solve(A) # inverse
solve(A, c(1, 2)) # solve Ax = b
det(A); diag(A); crossprod(A) # t(A) %*% A
eigen(A); svd(A); qr(A); chol(A)
outer(1:3, 1:3) # multiplication table
rowSums(m); colMeans(m); apply(m, 1, max)
10.3 Arrays (n-D)
a <- array(1:24, dim = c(2, 3, 4))
a[1, 2, 3]
dim(a)
apply(a, 3, sum)
aperm(a, c(3, 1, 2)) # permute dimensions