Matrices
Matrix M is a two-dimensional object
with n rows and m columns:
Matrix? a(1,1) a(1,2) ... a(1,m)
a(2,1) a(2,2) ... a(2,m)
... ... ... ...
a(n,1) a(n,2) ... a(n,m)
Create a matrix
We can create a matrix using:
● Function matrix()
○ M <- matrix(data = 1:4, nrow = 2, ncol = 2)
● By combining vectors cbind(), rbind()
○ M <- rbind(c(1,2), c(3,4))
● By altering dimension of a vector dim()
○ dim(v) <- c(2, 2)
Matrix properties
Matrix M holds different properties:
● Matrix dimension (rows, columns)
○ dim(M)
● Matrix row names
○ rownames(M)
● Matrix column names
○ colnames(M)
● We can access matrix properties by:
○ attributes(M)
Access matrix elements []
We can access matrix M elements using:
● Integer vector as index
○ M[c(1, 2, 3), c(1, 2)]
● Logical vector as index
○ M[c(TRUE, TRUE, TRUE), c(TRUE, TRUE, FALSE)]
● Character vector as index (if we assigned names to matrix elements)
○ M[c(“row1”, “row2”, “row3”), c(“col1”, “col2”,)]
● Range of indexes (slicing rows and columns)
○ M[1:3, 1:2]
Modifying a matrix
● Alter matrix elements
○ M[1, 3] <- 6 | M <- M[1:2, ]
● Transpose a matrix
○ M <- t(M)
● Append a row to matrix
○ M <- rbind(M, c(1, 2, 3))
● Append a column to matrix
○ M <- cbind(M, c(1, 2, 3))
● Alter matrix dimension
○ dim(M) <- c(1, 9)
Matrix arithmetics Element-wise multiplication
● Addition: M1 + M2
1 2 3 2 2 2 2 4 6
● Subtraction: M1 - M2
● Multiplication: M1 * M2
4 5 6 * 2 2 2 = 8 10 12
7 8 9 2 2 2 14 16 18
● Division: M1 / M2
● Using different functions:
log(M1) Matrix based multiplication
● Vector-matrix style
1 2 3 2 2 2 12 12 12
multiplication: M1 %*% M2
● ...
4 5 6 %*% 2 2 2 = 30 30 30
7 8 9 2 2 2 48 48 48
Matrix algebra
rbind(M1,M2)
cbind(M1,M2)
diag(M)
colSums(M) rowSums(M)
colMeans(M) rowMeans(M)
det(M)
solve(M)
eigen(M)
...
Summarizing a matrix
apply(matrix, margin, function)
margin = 1 margin = 2 sum
M
max
min
mean
median
sd
var
across rows across cols ...