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

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

问题描述

R 提供了三种类型来存储同类对象列表:vectormatrixarray.

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

据我所知:

  • vector 是一维数组的特例
  • matrix 是二维数组的特例
  • 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).

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

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和二维array没有区别:

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

matrix 只是一个更方便的构造函数,还有很多函数和方法只接受二维数组(也就是矩阵).

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.

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

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天全站免登陆