行、列與維度的名稱

矩陣與陣列各個維度的名稱可以使用 rownamescolnamesdimnames 函數來取得:

x.matrix <- matrix(1:6, nrow = 2, ncol = 3,
  dimnames = list(c("row1", "row2"),
  c("C.1", "C.2", "C.3")))
rownames(x.matrix)
[1] "row1" "row2"
colnames(x.matrix)
[1] "C.1" "C.2" "C.3"
dimnames(x.matrix)
[[1]]
[1] "row1" "row2"

[[2]]
[1] "C.1" "C.2" "C.3"

如果是陣列的話,用法也相同:

x.array <- array(1:24, dim = c(4, 3, 2), dimnames = list(
  X = c("A1","A2","A3","A4"),
  Y = c("B1", "B2", "B3"), Z = c("C1", "C2")))
rownames(x.array)
[1] "A1" "A2" "A3" "A4"
colnames(x.array)
[1] "B1" "B2" "B3"
dimnames(x.array)
$X
[1] "A1" "A2" "A3" "A4"

$Y
[1] "B1" "B2" "B3"

$Z
[1] "C1" "C2"

陣列索引

矩陣與高維度的陣列的索引用法跟一維的向量類似,只是索引的維度變高而已:

x.matrix[2, 1]
[1] 2
x.array[3, 2, 2]
[1] 19

也可以拿數值索引與維度的名稱混合使用:

x.matrix[2, c("C.2", "C.3")]
C.2 C.3 
  4   6
x.array[3, c("B2", "B3"), "C2"]
B2 B3 
19 23

若不指定維度的索引,就會選取整個維度的所有資料:

x.matrix[2, ]
C.1 C.2 C.3 
  2   4   6
x.array[3, 2, ]
C1 C2 
 7 19
x.array[3, , ]
    Z
Y    C1 C2
  B1  3 15
  B2  7 19
  B3 11 23

合併矩陣

假設我們有兩個矩陣:

x.matrix1 <- matrix(1:6, nrow = 3, ncol = 2)
x.matrix2 <- matrix(11:16, nrow = 3, ncol = 2)

如果使用 c 函數合併這兩個矩陣的話,所有的資料都會被轉換為一維的向量:

c(x.matrix1, x.matrix2)
[1]  1  2  3  4  5  6 11 12 13 14 15 16

cbindrbind 則可以讓資料保持矩陣的結構來合併:

cbind(x.matrix1, x.matrix2)
     [,1] [,2] [,3] [,4]
[1,]    1    4   11   14
[2,]    2    5   12   15
[3,]    3    6   13   16
rbind(x.matrix1, x.matrix2)
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
[4,]   11   14
[5,]   12   15
[6,]   13   16

陣列的運算

矩陣在搭配四則運算子(+-*/)時,會對矩陣中個別元素進行運算:

x.matrix1 + x.matrix2
     [,1] [,2]
[1,]   12   18
[2,]   14   20
[3,]   16   22
x.matrix1 * x.matrix2
     [,1] [,2]
[1,]   11   56
[2,]   24   75
[3,]   39   96

若要將矩陣轉置,可以使用 t 函數:

t(x.matrix1)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

而矩陣的乘法運算子是 %*%(內積)與 %o%(外積):

x.matrix1 %*% t(x.matrix1)
     [,1] [,2] [,3]
[1,]   17   22   27
[2,]   22   29   36
[3,]   27   36   45
1:3 %o% 4:6
     [,1] [,2] [,3]
[1,]    4    5    6
[2,]    8   10   12
[3,]   12   15   18

矩陣的外積也可以使用 outer 函數,它跟 %o% 運算子是一樣的:

outer(1:3, 4:6)
     [,1] [,2] [,3]
[1,]    4    5    6
[2,]    8   10   12
[3,]   12   15   18

冪次運算子(^)作用在矩陣上的時候,也是會對個別元素進行運算,所以在解反矩陣時,不能使用矩陣 -1 次方的方式計算:

m <- matrix(c(1, 0, 1, 5, -3, 1, 2, 4, 7), nrow = 3)
m ^ -1
     [,1]       [,2]      [,3]
[1,]    1  0.2000000 0.5000000
[2,]  Inf -0.3333333 0.2500000
[3,]    1  1.0000000 0.1428571

反矩陣要使用 solve 函數來計算:

m.inv <- solve(m)
m.inv
     [,1] [,2] [,3]
[1,]  -25  -33   26
[2,]    4    5   -4
[3,]    3    4   -3
m %*% m.inv
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1