数组是一种数据结构,它可以在二维以上存储相同类型的数据。
向量、矩阵和数组之间唯一的区别是
- 向量是一维数组
- 矩阵是二维数组
- 数组可以有二维以上
在学习数组之前,请确保您了解 R 矩阵 和 R 向量。
在 R 中创建数组
在 R 中,我们使用 array() 函数来创建数组。
array() 函数的语法是
array(vector, dim = c(nrow, ncol, nmat))
这里,
- vector - 相同类型的数据项
nrow- 行数ncol- 列数nmat-nrow * ncol维度的矩阵数量
让我们看一个例子,
# create two 2 by 3 matrix
array1 <- array(c(1:12), dim = c(2,3,2))
print(array1)
输出
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
, , 2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
在上面的示例中,我们使用 array() 函数创建了一个名为 array1 的数组。请注意 array() 中传递的参数,
array(c(1:15), dim = c(2,3,2))
这里,
c(1:12)- 一个值从 1 到 12 的向量dim = c(2,3,2)- 创建两个 2 行 3 列的矩阵
最后,打印出从 1 到 12,以两个 2 行 3 列矩阵排列的数字。
访问数组元素
我们使用向量索引运算符 [ ] 来访问 R 中数组的特定元素。
访问数组元素的语法是
array[n1, n2, mat_level]
这里,
n1- 指定行位置n2- 指定列位置mat_level- 指定矩阵级别
让我们看一个例子,
# create two 2 by 3 matrix
array1 <- array(c(1:12), dim = c(2,3,2))
print(array1)
# access element at 1st row, 3rd column of 2nd matrix
cat("\nDesired Element:", array1[1, 3, 2])
输出
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
, , 2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
Desired Element: 11
在上面的示例中,我们创建了一个名为 array1 的数组,其中包含两个 2 行 3 列的矩阵。请注意索引运算符 [] 的使用,
array1[1, 3, 2]
在这里,[1, 3, 2] 指定我们正在尝试访问第 2 个矩阵的第 1 行、第 3 列中存在的元素,即 11。
访问整行或整列
在 R 中,我们还可以根据 [] 中传递的值访问整行或整列。
[c(n), ,mat_level]- 返回第 n 行的所有元素。[ ,c(n), mat_level]- 返回第 n 列的所有元素。
例如,
# create a two 2 by 3 matrix
array1 <- array(c(1:12), dim = c(2,3,2))
print(array1)
# access entire elements at 2nd column of 1st matrix
cat("\n2nd Column Elements of 1st matrix:", array1[,c(2),1])
# access entire elements at 1st row of 2nd matrix
cat("\n1st Row Elements of 2nd Matrix:", array1[c(1), ,2])
输出
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
, , 2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
2nd Column Elements of 1st matrix: 3 4
1st Row Elements of 2nd Matrix: 7 9 11
这里,
array1[,c(2),1]- 访问第 1 个矩阵的第 2 列元素array1[c(1), ,2]- 访问第 2 个矩阵的第 1 行
检查元素是否存在
在 R 中,我们使用 %in% 运算符来检查指定元素是否存在于矩阵中,并返回一个布尔值。
TRUE- 如果指定元素存在于矩阵中FALSE- 如果指定元素不存在于矩阵中
例如,
# create a two 2 by 3 matrix
array1 <- array(c(1:12), dim = c(2,3,2))
11 %in% array1 # TRUE
13 %in% array1 # FALSE
输出
[1] TRUE [2] FALSE
这里,
- 11 存在于 array1 中,因此该方法返回
TRUE - 13 不存在于 array1 中,因此该方法返回
FALSE
R 中数组的长度
在 R 中,我们可以使用 length() 函数来查找数组中存在的元素数量。例如,
# create a two 2 by 3 matrix
array1 <- array(c(1:12), dim = c(2,3,2))
# find total elements in array1 using length()
cat("Total Elements:", length(array1))
输出
Total Elements: 12
在这里,我们使用 length() 来查找 array1 的长度。由于有两个 2 行 3 列的矩阵,length() 函数返回 12。