boulder_ruby
boulder_ruby

Reputation: 39695

Are arrays in Ruby and similarly typed languages vectors?

R wraps csv'd lists of numbers (comma separated values i.e. 1, 2, 3) in the c() function, a part of the R core library, which converts csv'd lists of numbers into vectors.

These vectors look like Ruby or Java arrays, with the exception that these csv'd lists are wrapped in c() rather than []. It seems like arrays are really a subset of vectors. Is it true? And if so, what does this mean when it comes to arrays and matrices?

One discussion on the subject I found stated that arrays are static vectors. But in Ruby, arrays aren't static. In Ruby, arrays are vectors?

Upvotes: 2

Views: 486

Answers (1)

Josh O'Brien
Josh O'Brien

Reputation: 162321

Yep, in R an array is just a vector equipped with attributes that give the dimensions of the array.

From ?array:

Details:

An array in R can have one, two or more dimensions. It is simply a vector which is stored with additional attributes giving the dimensions (attribute ‘"dim"’) and optionally names for those dimensions (attribute ‘"dimnames"’).

A two-dimensional array is the same thing as a ‘matrix’.

One-dimensional arrays often look like vectors, but may be handled differently by some functions: ‘str’ does distinguish them in recent versions of R.

The ‘"dim"’ attribute is an integer vector of length one or more containing non-negative values: the product of the values must match the length of the array.

Maybe the easiest way to see this for yourself is to have a look at a vector, a matrix, and a higher dimensional array, like this:

a <- array(1:12, dim=c(2,2,3))
m <- matrix(1:4, ncol=2)
v <- c(1,2)

is(a)
# [1] "array"     "matrix"    "structure" "vector"    "vector"  
is(m)
# [1] "matrix"    "array"     "structure" "vector"
is(v)
# [1] "numeric" "vector" 

attributes(a)
# $dim
# [1] 2 2 3
attributes(m)
# $dim
# [1] 2 2
attributes(v)
# NULL

## Finally, try this
v <- 1:12
dim(v) <- c(2,2,3)
v

Upvotes: 3

Related Questions