向量,矩阵和数组数据类型之间有何区别? [英] What are the differences between vector, matrix and array data types?

查看:297
本文介绍了向量,矩阵和数组数据类型之间有何区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R带有三种类型的存储同类对象的列表:vectormatrixarray.

R comes with three types to store lists of homogenous objects: vector, matrix and array.

据我所知:

  • vector是一维数组的特殊情况
  • matrix是2维数组的特例
  • array也可以具有任何尺寸级别(包括1和2).
  • vector is special cases for 1 dimension arrays
  • matrix is a special case for 2 dimensions arrays
  • array can also have any dimension level (including 1 and 2).

在向量上使用1D数组,在矩阵上使用2D数组有什么区别?我们需要在两者之间进行转换,还是会自动发生?

What is the difference between using 1D arrays over vectors and 2D arrays over matrices? Do we need to cast between those, or will it happen automagically?

推荐答案

matrix和2D array之间没有区别:

There is no difference between a matrix and a 2D array:

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

matrix只是一个更方便的构造方法,并且有许多仅接受2D数组(也称为矩阵)的函数和方法.

matrix is just a more convenient constructor, and there are many functions and methods that only accept 2D arrays (a.k.a. matrices).

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

Internally, arrays are just vectors with a dimension attribute:

...
> 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

要引用语言定义:

矩阵和数组只是具有属性dim的向量 可选地dimnames附加到载体上.

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

[...]

dim属性用于实现数组.的内容 数组以列优先顺序存储在向量中,而dim 属性是整数的向量,指定整数的相应范围 数组. R确保向量的长度是 尺寸的长度.一维或多维的长度 可能为零.

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.

向量与一维数组不同,因为后者 具有长度为1的暗淡属性,而前者没有暗淡 属性.

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.

这篇关于向量,矩阵和数组数据类型之间有何区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆