
5-1 矩阵Matrix
若是将向量想成线,则可将矩阵想成面,如上图所示。对R程序设计师而言,首先要思考的是如何建立矩阵。
5-1-1 建立矩阵
建立矩阵可使用matrix()函数,格式如下所示。
matrix(data, nrow = ?, ncol = ?, byrow = logical, dimnames = NULL)
❑ data:数据。
❑ nrow:预计行的数量。
❑ ncol:预计列的数量。
❑ byrow:逻辑值。默认是FALSE,表示先按列(Column)填数据,第1列填满再填第2列,其他依此类推,因此,若先填列则可省略此参数。如果是TRUE则先填行(Row),第1行填满再填第2行,其他依此类推。
❑ dimnames:矩阵的属性。
实例ch5_1:建立first.matrix,数据为1:12,4行的矩阵。

实例ch5_2:建立second.matrix,数据为1:12,4行的矩阵,byrow设为TRUE。

实例ch5_3:建立third.matrix,数据为1:12,4行的矩阵,byrow设为FALSE。这个实例的执行结果与ch5_1相同。

5-1-2 认识矩阵的属性
使用str()函数也可以查看矩阵对象的结构。
实例ch5_4:使用str()函数查看first.matrix和second.matrix的结构。

使用nrow()函数可以得到矩阵的行数。
实例ch5_5:使用nrow()函数查看first.matrix和second.matrix的行数。


使用ncol()函数可以得到矩阵的列数。
实例ch5_6:使用ncol()函数查看first.matrix和second.matrix的列数。

使用dim()函数则可以获得矩阵对象的行数和列数。
实例ch5_7:使用dim()函数查看first.matrix和second.matrix的行数和列数。

此外,length()函数也可用于取得矩阵(Matrix)或三维或多维数组(Array)对象的元素个数。
实例ch5_8:取得first.matrix和second.matrix的元素个数。

is.matrix()函数可用于检查对象是否是矩阵(Matrix)。
实例ch5_9:检查first.matrix和second.matrix是否是矩阵(Matrix)。

is.array()函数可用于检查对象是否是Array。
实例ch5_10:检查first.matrix和second.matrix是否是Array。

5-1-3 将向量组成矩阵
R语言提供的rbind()函数可将两个或多个向量组成矩阵,每个向量各自占用一行。
实例ch5_11:使用rbind()函数,简单地将两个向量组成矩阵的实例。

由上图可以看到矩阵左边保留了原向量对象的名称,后面章节会介绍如何使用这个向量名称。
实例ch5_12:矩阵也可以和向量组合成矩阵。

在上一章笔者讲解了有关baskets.NBA2016.Jordon和baskets.NBA2016.Lin这两个向量对象,下列是将这两个对象组成矩阵的实例。
实例ch5_13:将baskets.NBA2016.Jordon和baskets.NBA2016.Lin组成矩阵的实例。

cbind()函数可将两个或多个向量组成矩阵,功能类似rbind()。不过,它是以每个向量各占一列的方式来组织向量的。
实例ch5_14:使用cbind()函数重新设计实例ch5_11。


实例ch5_15:使用cbind()将两个向量与1个矩阵组成矩阵的应用实例。
