What are the differences between vector, matrix and array data types? What are the differences between vector, matrix and array data types? arrays arrays

What are the differences between vector, matrix and array data types?


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.