What are the differences between vector, matrix an

2020-02-07 17:54发布

问题:

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

As far as I can tell:

  • 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?

回答1:

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

To cite the 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.



回答2:

In java, the main difference between vector and array is Memory Allocation.

Vectors are dynamically allocated. They contain dynamic lists of references to the created other objects and can hold data from different type of object/data types. Their size can easily vary with respect to the object pushed to the vector.

Array, on the other side, they are static. They group data with a fixed primitive object type and with a fixed size. When the chunk size is full, they doubles the chunk size of array pool.

Matrix, are the 2-Dimensional array at the end.



标签: arrays r types