gpt4 book ai didi

arrays - 向量、矩阵和数组数据类型之间有什么区别?

转载 作者:行者123 更新时间:2023-12-01 22:18:12 27 4
gpt4 key购买 nike

R 提供了三种类型来存储同质对象列表:向量矩阵数组

据我所知:

  • 向量是一维数组的特殊情况
  • 矩阵是二维数组的特例
  • 数组还可以具有任意维度级别(包括 1 和 2)。

在向量上使用一维数组和在矩阵上使用二维数组有什么区别?我们是否需要在它们之间进行转换,还是会自动发生?

最佳答案

矩阵和二维数组之间没有区别:

> x <- matrix(1:10, 2)
> y <- array(1:10, c(2, 5))
> identical(x, y)
[1] TRUE
...

matrix 只是一个更方便的构造函数,有许多函数和方法只接受二维数组(也称为矩阵)。

在内部,数组只是具有维度属性的向量:

...
> attributes(x)
$dim
[1] 2 5

> dim(x) <- NULL
> x
[1] 1 2 3 4 5 6 7 8 9 10
> z <- 1:10
> dim(z) <- c(2, 5)
> is.matrix(z)
[1] TRUE

引用language definition :

Matrices and arrays are simply vectors with the attribute dim and optionally dimnames attached to the vector.

[...]

The dim attribute is used to implement arrays. The content of the array is stored in a vector in column-major order and the dim attribute is a vector of integers specifying the respective extents of the array. R ensures that the length of the vector is the product of the lengths of the dimensions. The length of one or more dimensions may be zero.

A vector is not the same as a one-dimensional array since the latter has a dim attribute of length one, whereas the former has no dim attribute.

关于arrays - 向量、矩阵和数组数据类型之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33982640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com