矩阵
x <- 1:20
x
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
m <- matrix(x,4,5)
m
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
m <- matrix(x,4,5,byrow=T) #按行排列
m
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 6 7 8 9 10
[3,] 11 12 13 14 15
[4,] 16 17 18 19 20
rnames <- c("R1","R2","R3","R4")
cnames <- c("C1","C2","C3","C4","C5")
dimnames(m) <- list(rnames,cnames)
m
C1 C2 C3 C4 C5
R1 1 2 3 4 5
R2 6 7 8 9 10
R3 11 12 13 14 15
R4 16 17 18 19 20
dim(x) #显示向量维数
NULL
dim(x) <- c(4,5) #将一维向量定义维数获得矩阵
x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
数组(向量一维、矩阵二维、数组三维)
x <- 1:20
dim(x) <- c(2,2,5)
x
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
, , 3
[,1] [,2]
[1,] 9 11
[2,] 10 12
, , 4
[,1] [,2]
[1,] 13 15
[2,] 14 16
, , 5
[,1] [,2]
[1,] 17 19
[2,] 18 20
dim1 <- c("A1","A2")
dim2 <- c("B1","B2","B3")
dim3 <- c("C1","C2","C3","C4")
z <- array(1:24,c(2,3,4),dimnames=list(dim1,dim2,dim3))
z
, , C1
B1 B2 B3
A1 1 3 5
A2 2 4 6
, , C2
B1 B2 B3
A1 7 9 11
A2 8 10 12
, , C3
B1 B2 B3
A1 13 15 17
A2 14 16 18
, , C4
B1 B2 B3
A1 19 21 23
A2 20 22 24
矩阵的索引
m
C1 C2 C3 C4 C5
R1 1 2 3 4 5
R2 6 7 8 9 10
R3 11 12 13 14 15
R4 16 17 18 19 20
m[1,2]
[1] 2
m[1,c(2,3,4)]
C2 C3 C4
2 3 4
m[c(2:4),c(2,3)]
C2 C3
R2 7 8
R3 12 13
R4 17 18
m[2,] #访问第二行
C1 C2 C3 C4 C5
6 7 8 9 10
m[,2] #访问第二列
R1 R2 R3 R4
2 7 12 17
m[-1,2] #去除第一行,再取第二列
R2 R3 R4
7 12 17
m["R1","C2"]
[1] 2
矩阵的运算
m
C1 C2 C3 C4 C5
R1 1 2 3 4 5
R2 6 7 8 9 10
R3 11 12 13 14 15
R4 16 17 18 19 20
m+1
C1 C2 C3 C4 C5
R1 2 3 4 5 6
R2 7 8 9 10 11
R3 12 13 14 15 16
R4 17 18 19 20 21
m*2
C1 C2 C3 C4 C5
R1 2 4 6 8 10
R2 12 14 16 18 20
R3 22 24 26 28 30
R4 32 34 36 38 40
m+m
C1 C2 C3 C4 C5
R1 2 4 6 8 10
R2 12 14 16 18 20
R3 22 24 26 28 30
R4 32 34 36 38 40
n <- matrix(1:20,5,4)
n
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
m+n #会报错,行列不一致
colSums(m)
C1 C2 C3 C4 C5
34 38 42 46 50
rowSums(m)
R1 R2 R3 R4
15 40 65 90
colMeans(m)
C1 C2 C3 C4 C5
8.5 9.5 10.5 11.5 12.5
rowMeans(m)
R1 R2 R3 R4
3 8 13 18
#内积 对应位置相乘
n <- matrix(1:9,3,3)
t <- matrix(2:10,3,3)
n * t
[,1] [,2] [,3]
[1,] 2 20 56
[2,] 6 30 72
[3,] 12 42 90
#外积 线性代数矩阵乘积
n %*% t
[,1] [,2] [,3]
[1,] 42 78 114
[2,] 51 96 141
[3,] 60 114 168
diag(n) #取方阵对角线
[1] 1 5 9
t(m) #转至矩阵
R1 R2 R3 R4
C1 1 6 11 16
C2 2 7 12 17
C3 3 8 13 18
C4 4 9 14 19
C5 5 10 15 20