需要的储备知识:
矩阵与数组
(1)构建矩阵以及按顺序排列
> 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,mrow = 4,mcol = 5)
Error in matrix(x, mrow = 4, mcol = 5) : 参数没有用(mrow = 4, mcol = 5)
> m <- matrix(x,nrow = 4,ncol = 5) #构建矩阵
> m <- matrix(1:20,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,nrow = 4,ncol = 6) #个数要符合矩阵的个数
Warning message:
In matrix(x, nrow = 4, ncol = 6) : 数据长度[20]不是矩阵列数[6]的整倍数
> m <- matrix(x,nrow = 4,ncol = 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
> m <- matrix(x,nrow = 4,ncol = 5,byrow = F) #按列排
> 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
#cbind: 按列进行合并,即叠加所有列,m列的矩阵与n列的矩阵cbind()最后变成m+n列,合并前提:#cbind(a, c)中矩阵a、c的行数必需相符
#rbind: 按行进行合并,就是行的叠加,m行的矩阵与n行的矩阵rbind()最后变成m+n行,合并前提:#rbind(a, c)中矩阵a、c的列数必需相符
> a <- matrix(1:12, 3, 4)
> print(a)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
>
> b <- matrix(-1:-12, 3, 4)
> print(b)
[,1] [,2] [,3] [,4]
[1,] -1 -4 -7 -10
[2,] -2 -5 -8 -11
[3,] -3 -6 -9 -12
>
> x=cbind(a,b)
> print(x)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 4 7 10 -1 -4 -7 -10
[2,] 2 5 8 11 -2 -5 -8 -11
[3,] 3 6 9 12 -3 -6 -9 -12
>
> y=rbind(a,b)
> print(y)
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
[4,] -1 -4 -7 -10
[5,] -2 -5 -8 -11
[6,] -3 -6 -9 -12
>
>
> c <- matrix(-1:-20, 4, 5)
> print(c)
[,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
>
> x2=cbind(a,c)
Error in cbind(a, c) : 矩阵的行数必需相符(见arg2)
> print(x2)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1 4 7 10 -1 -4 -7 -10 -13
[2,] 2 5 8 11 -2 -5 -8 -11 -14
[3,] 3 6 9 12 -3 -6 -9 -12 -15
>
> y2=rbind(a,c)
Error in rbind(a, c) : 矩阵的列数必需相符(见arg2)
> print(y2)
Error in print(y2) : 找不到对象'y2'
>
(2)矩阵运算
> m + 1 #所有元素加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
> 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\
错误: unexpected input in "m\"
> 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 + n #矩阵相加要行列相等
Error in m + n : 非整合陈列
> m[,1]
R1 R2 R3 R4
1 6 11 16
> t <- m[,1]
> sum(t) #求第一列的和
[1] 34
> colSums(m) #计算每一列的和
C1 C2 C3 C4 C5
34 38 42 46 50
> rowSum(m)
Error in rowSum(m) : 没有"rowSum"这个函数
> 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*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(n) #函数t对矩阵进行转置
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
б²=SSE/N-p-1(n是样本数量,p是自由度)
SSE=(y-xβ)^t(y-xβ)
β即下图中的Estimate列值
x1即对应的β0,也是32行,1列,x1 所有元素全是1(易错,易遗漏)
答:由方差分析结果可知,F的值13.93,p值3.793e-07