Arrays and Matrices

Table of Contents

Overview

A multiply subscripted collection of data entries.

x = 1:9
dim(x) <- c(3, 3)
x
array(1:9, dim = c(3, 3))
matrix(1:9, nrow = 3, ncol = 3)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
x = 1:3
y = 1:3 * 10
z = 1:3 * 100
cbind(x, y, z)                      # column named are bound as their variable name
cbind(col1 = x, col2 = y, col3 = z) # specify column names explicitly
     x  y   z
[1,] 1 10 100
[2,] 2 20 200
[3,] 3 30 300
     col1 col2 col3
[1,]    1   10  100
[2,]    2   20  200
[3,]    3   30  300
x <- matrix(1:9, 3, 3)
x
i <- array(c(1:3,3:1), dim = c(3, 2))
x[i] # === c(x[1, 3], x[2, 2], x[3, 1])
x[i] <- 0
x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
[1] 7 5 3
     [,1] [,2] [,3]
[1,]    1    4    0
[2,]    2    0    8
[3,]    0    6    9
A <- matrix(1:4, 2, 2)
B <- matrix(4:1, 2, 2)
A * B     # element-wise product
A %*% B   # matrix product
solve(A)  # inverse
     [,1] [,2]
[1,]    4    6
[2,]    6    4
     [,1] [,2]
[1,]   13    5
[2,]   20    8
     [,1] [,2]
[1,]   -2  1.5
[2,]    1 -0.5
A <- matrix(1:4, 2, 2)
# To vector
as.vector(A)
c(A)
[1] 1 2 3 4
[1] 1 2 3 4

Remove column names howto

colnames(M) <- NULL

Convert a matrix to a list howto

foo <- cbind(c(1,2,3), c(15,16,17))
as.list(data.frame(t(foo)))
$X1
[1]  1 15

$X2
[1]  2 16

$X3
[1]  3 17

Get a matrix indices with which() howto

m = rbind(c(1, 2, 3),
          c(4, 5, 6),
          c(7, 8, 9))
which(m %% 2 == 0, arr.ind = TRUE)
     row col
[1,]   2   1
[2,]   1   2
[3,]   3   2
[4,]   2   3