统计分析:使用 R/R/矩阵的介绍
外观
< 统计分析:使用 R 的介绍 | R
许多统计理论使用矩阵代数。虽然本书不需要详细了解矩阵,但了解 R 如何处理矩阵非常有用。
本质上,矩阵(复数:矩阵)是向量的二维等价物。换句话说,它是一个数字的矩形网格,按行和列排列。在 R 中,可以使用matrix()函数创建矩阵对象,该函数将一个数字向量(用于填充矩阵)作为第一个参数,并将行数和列数分别作为第二个和第三个参数。
R 也可以使用数组对象,它们类似于矩阵,但可以有超过 2 个维度。这些对于表格特别有用:一种包含根据各种标准分类的数据计数的数组。这些“列联表”的示例如下所示的HairEyeColor和Titanic表。
[]可用于访问矩阵或数组中的单个元素或元素集。这是通过用逗号分隔括号内的数字来完成的。例如,对于矩阵,需要指定行索引,然后是一个逗号,然后是列索引。如果行索引为空,则假定需要所有行,列索引也是如此。m <- matrix(1:12, 3, 4) #Create a 3x4 matrix filled with numbers 1 to 12
m #Display it!
m*2 #Arithmetic, just like with vectors
m[2,3] #Pick out a single element (2nd row, 3rd column)
m[1:2, 2:4] #Or a range (rows 1 and 2, columns 2, 3, and 4.)
m[,1] #If the row index is missing, assume all rows
m[1,] #Same for columns
m[,2] <- 99 #You can assign values to one or more elements
m #See!
###Some real data, stored as "arrays"
HairEyeColor #A 3D array
HairEyeColor[,,1] #Select only the males to make it a 2D matrix
Titanic #A 4D array
Titanic[1:3,"Male","Adult",] #A matrix of only the adult male passengers> m <- matrix(1:12, 3, 4) #Create a 3x4 matrix filled with numbers 1 to 12
> m #Display it!
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> m*2 #Arithmetic, just like with vectors
[,1] [,2] [,3] [,4]
[1,] 2 8 14 20
[2,] 4 10 16 22
[3,] 6 12 18 24
> m[2,3] #Pick out a single element (2nd row, 3rd column)
[1] 8
> m[1:2, 2:4] #Or a range (rows 1 and 2, columns 2, 3, and 4.)
[,1] [,2] [,3]
[1,] 4 7 10
[2,] 5 8 11
> m[,1] #If the row index is missing, assume all rows
[1] 1 2 3
> m[1,] #Same for columns
[1] 1 4 7 10
> m[,2] <- 99 #You can assign values to one or more elements
> m #See!
[,1] [,2] [,3] [,4]
[1,] 1 99 7 10
[2,] 2 99 8 11
[3,] 3 99 9 12
> ###Some real data, stored as "arrays"
> HairEyeColor #A 3D array
, , Sex = Male
Eye
Hair Brown Blue Hazel Green
Black 32 11 10 3
Brown 53 50 25 15
Red 10 10 7 7
Blond 3 30 5 8
, , Sex = Female
Eye
Hair Brown Blue Hazel Green
Black 36 9 5 2
Brown 66 34 29 14
Red 16 7 7 7
Blond 4 64 5 8
> HairEyeColor[,,1] #Select only the males to make it a 2D matrix
Eye
Hair Brown Blue Hazel Green
Black 32 11 10 3
Brown 53 50 25 15
Red 10 10 7 7
Blond 3 30 5 8
> Titanic #A 4D array
, , Age = Child, Survived = No
Sex
Class Male Female
1st 0 0
2nd 0 0
3rd 35 17
Crew 0 0
, , Age = Adult, Survived = No
Sex
Class Male Female
1st 118 4
2nd 154 13
3rd 387 89
Crew 670 3
, , Age = Child, Survived = Yes
Sex
Class Male Female
1st 5 1
2nd 11 13
3rd 13 14
Crew 0 0
, , Age = Adult, Survived = Yes
Sex
Class Male Female
1st 57 140
2nd 14 80
3rd 75 76
Crew 192 20
> Titanic[1:3,"Male","Adult",] #A matrix of only the adult male passengers
Survived
Class No Yes
1st 118 57
2nd 154 14
3rd 387 75