R语言 多维数组

R语言 多维数组

数组是R的数据对象,可以存储两个以上维度的数据。举例来说。如果我们创建一个维度为(2,3,4)的数组,那么它将创建4个矩形矩阵,每个矩阵有2行和3列。这些类型的数组被称为多维数组。数组只能存储数据类型。

创建一个多维数组

一个数组是用 array() 函数创建的。它接受向量作为输入,使用dim参数中的值来创建一个数组。一个多维数组可以通过定义 ‘dim ‘参数的值作为所需的维数来创建。

语法

MArray = array(c(vec1, vec2), dim)
R

例子

# Create two vectors of different lengths.
vector1 <- c(5, 9, 3)
vector2 <- c(10, 11, 12, 13, 14, 15)
  
# Take these vectors as input to the array.
result <- array(c(vector1, vector2), dim = c(3, 3, 2))
print(result)
R

输出

, , 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
R

命名列和行

我们可以通过使用 dimnames 参数给数组中的行、列和矩阵命名。

例子

# Create two vectors of different lengths.
vector1 <- c(5, 9, 3)
vector2 <- c(10, 11, 12, 13, 14, 15)
column.names <- c("COL1", "COL2", "COL3")
row.names <- c("ROW1", "ROW2", "ROW3")
matrix.names <- c("Matrix1", "Matrix2")
  
# Take these vectors as input to the array.
result <- array(c(vector1, vector2), dim = c(3, 3, 2),
                  dimnames = list(row.names, column.names,
                  matrix.names))
print(result)
R

输出

, , Matrix1

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

, , Matrix2

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

操纵数组元素

由于数组是由多个维度的矩阵组成的,对数组元素的操作是通过访问矩阵的元素来进行的。有各种不同的操作可以在数组上执行。

例子

# Create two vectors of different lengths.
vector1 <- c(5, 9, 3)
vector2 <- c(10, 11, 12, 13, 14, 15)
  
# 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(vector1, vector2), dim = c(3, 3, 2))
  
# create matrices from these arrays.
matrix1 <- array1[,,2]
matrix2 <- array2[,,2]
  
# Add the matrices.
result <- matrix1 + matrix2
print(result)
R

输出

     [,1] [,2] [,3]
[1,]   10   20   26
[2,]   18   22   28
[3,]    6   24   30
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册