Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...