R 语言中的矩阵是按列存储(column-major order storage)的。
> matrix(1:6, nrow = 3, ncol = 2)
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
若想按行存储:
> matrix(1:6, nrow = 3, ncol = 2, byrow = TRUE)
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
> cbind(1:3, 4:6)
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> rbind(1:3, 4:6)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
> (x = matrix(1:12, nrow = 3, ncol = 4))
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> x[1:2, c(2,4)]
[,1] [,2]
[1,] 4 10
[2,] 5 11
> x[1:2, c(2,4)] = 21:24
> x
[,1] [,2] [,3] [,4]
[1,] 1 21 7 23
[2,] 2 22 8 24
[3,] 3 6 9 12
Matrix 的 value 可以像 vector 一样参与运算,从而进行修改:
> (x = matrix(1:4, nrow = 2, ncol = 2))
[,1] [,2]
[1,] 1 3
[2,] 2 4
> x + x^2
[,1] [,2]
[1,] 2 12
[2,] 6 20
Used to compute row or column summaries:
1 → 对行操作
2 → 对列操作
> x = matrix(1:4, nrow = 2, ncol = 2)
> x
[,1] [,2]
[1,] 1 3
[2,] 2 4
> apply(x, 1, mean)
[1] 2 3
> apply(x, 2, function(x) sum(x^2))
[1] 5 25
Used to sweep out computed summaries:
# 创建一个 3x4 的矩阵
mat <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), nrow = 3, ncol = 4)
# 计算矩阵的每列均值
col_means <- colMeans(mat)
# 从矩阵的每个元素中减去其所在列的均值
centered_mat <- sweep(mat, 2, col_means)
> centered_mat
[,1] [,2] [,3] [,4]
[1,] -1 -1 -1 -1
[2,] 0 0 0 0
[3,] 1 1 1 1
用于求解线性方程组或计算矩阵的逆。当提供一个矩阵作为参数时,solve() 函数计算该矩阵的逆矩阵(如果存在)。当提供一个线性方程组(由系数矩阵和常数向量表示)时,solve() 函数找到该线性方程组的解。
# 创建一个 2x2 方阵
mat <- matrix(c(2, 1, 3, 4), nrow = 2, ncol = 2)
# 计算矩阵的逆
inv_mat <- solve(mat)
# 创建一个线性方程组的常数向量
b <- c(5, 6)
# 解线性方程组:Ax = b,其中 A 是系数矩阵,x 是解向量,b 是常数向量
x <- solve(mat, b)