📜  R编程中的数组与矩阵

📅  最后修改于: 2022-05-13 01:55:33.563000             🧑  作者: Mango

R编程中的数组与矩阵

数据结构是一种在计算机中组织数据的特殊方式,以便可以有效地使用它。这个想法是减少不同任务的空间和时间复杂性。 R 编程中的数据结构是用于保存多个值的工具。 R 中两个最重要的数据结构是数组和矩阵。

R中的数组

数组是 R 中包含大于或等于 1 维的数据存储对象。数组只能包含一种数据类型。 array()函数是一个内置函数,它将输入作为向量并根据dim参数排列它们。 Array 是一个可迭代对象,其中数组元素被单独索引、访问和修改。可以使用类似的结构和维度对数组执行操作。一维数组在 R 中称为向量。二维数组称为矩阵。

示例

Python3
# R program to illustrate an array
 
# creating a vector
vector1 <- c("A", "B", "C")
# declaring a character array
uni_array <- array(vector1)
print("Uni-Dimensional Array")
print(uni_array)
 
# creating another vector
vector <- c(1:12)
# declaring 2 numeric multi-dimensional
# array with size 2x3
multi_array <- array(vector, dim = c(2, 3, 2))
print("Multi-Dimensional Array")
print(multi_array)


Python3
# R program to illustrate a matrix
 
A = matrix(
    # Taking sequence of elements
    c(1, 2, 3, 4, 5, 6, 7, 8, 9),
     
    # No of rows and columns
    nrow = 3, ncol = 3, 
 
    # By default matrices are
    # in column-wise order
    # So this parameter decides
    # how to arrange the matrix         
    byrow = TRUE                            
)
 
print(A)


输出:

[1] "Uni-Dimensional Array"
[1] "A" "B" "C"
[1] "Multi-Dimensional Array"
, , 1

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

, , 2

     [,1] [,2] [,3]
[1,]    7    9   11
[2,]    8   10   12

R中的矩阵

R 中的矩阵是一种类似表格的结构,由以固定数量的行和列排列的元素组成。所有元素都属于一种数据类型。 R 包含一个内置函数matrix()来创建一个矩阵。可以通过提供行和列的索引来访问矩阵的元素。可以对具有相同维度的矩阵执行算术运算、加法、减法和乘法运算。矩阵可以很容易地转换为数据帧 CSV。

例子:

Python3

# R program to illustrate a matrix
 
A = matrix(
    # Taking sequence of elements
    c(1, 2, 3, 4, 5, 6, 7, 8, 9),
     
    # No of rows and columns
    nrow = 3, ncol = 3, 
 
    # By default matrices are
    # in column-wise order
    # So this parameter decides
    # how to arrange the matrix         
    byrow = TRUE                            
)
 
print(A)

输出:

[,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

数组与矩阵

ArraysMatrices
Arrays can contain greater than or equal to 1 dimensions.Matrices contains 2 dimensions in a table like structure.
Array is a homogeneous data structure.Matrix is also a homogeneous data structure.
It is a singular vector arranged into the specified dimensions.It comprises of multiple equal length vectors stacked together in a table.
array() function can be used to create matrix by specifying the third dimension to be 1.matrix() function however can be used to create at most 2-dimensional array.
Arrays are superset of matrices.Matrices are a subset, special case of array where dimensions is two.
Limited set of collection-based operations.Wide range of collection operations possible.
Mostly, intended for storage of data.Mostly, matrices are intended for data transformation.