R语言基础教程 | 数据结构—数组

2021-06-11  本文已影响0人  生信师姐

数组(array)与矩阵类似,但是维度可以大于2。数组可通过array函数创建,形式如下:

array(data = NA, dim = length(data), dimnames = NULL)

其中data包含了数组中的数据,dim是一个数值型向量,给出了各个维度下标的最大值,而dimnames是可选的、各维度名称标签的列表。

下面将创建的每两个3×3矩阵的数组,具有3行3列。

1.数组的创建

> # 创建两个不同长度的向量
> vector1 <- c(5,9,3)
> vector2 <- c(10,11,12,13,14,15)
> 
> # 把这些向量作为数组的输入
> result <- array(c(vector1,vector2),dim=c(3,3,2))
> result
, , 1

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   11   14
[3,]    3   12   15

, , 2

     [,1] [,2] [,3]
[1,]    5   10   13
[2,]    9   11   14
[3,]    3   12   15

2.命名列和行

我们可以通过使用dimnames参数给予名称添加到数组中的行,列和矩阵。

> column.names <- c("COL1","COL2","COL3")
> row.names <- c("ROW1","ROW2","ROW3")
> matrix.names <- c("Matrix1","Matrix2")
> result <- array(c(vector1,vector2),dim=c(3,3,2),dimnames = list(column.names,row.names,matrix.names))
> result
, , Matrix1

     ROW1 ROW2 ROW3
COL1    5   10   13
COL2    9   11   14
COL3    3   12   15

, , Matrix2

     ROW1 ROW2 ROW3
COL1    5   10   13
COL2    9   11   14
COL3    3   12   15

3.访问数组元素

访问数组是用[]索引。

> # 打印数组第二个矩阵的第三行
> result[3,,2]
ROW1 ROW2 ROW3 
   3   12   15 


> # 打印第1矩阵的第1行和第3列中的元素。
> result[1,3,1]
[1] 13


> # 打印第二个矩阵
> result[,,2]
     ROW1 ROW2 ROW3
COL1    5   10   13
COL2    9   11   14
COL3    3   12   15

4.操纵数组元素

# Take these vectors as input to the array.
> array1 <- array(c(vector1,vector2),dim=c(3,3,2))



> # Create two vectors of different lengths.
> vector3 <- c(9,1,0)
> vector4 <- c(6,0,11,3,14,1,2,6,9)
> array2 <- array(c(vector3,vector4),dim=c(3,3,2))



> # 从这些数组创建矩阵
> matrix1 <- array1[,,2]
> matrix2 <- array2[,,2]



> # 矩阵相加.
> result <- matrix1+matrix2
> result
     [,1] [,2] [,3]
[1,]    7   19   19
[2,]   15   12   14
[3,]   12   12   26

上一篇 下一篇

猜你喜欢

热点阅读