Skip to content
Prev 240545 / 398500 Next

About 5.1 Arrays

Hi Daniel,

Thanks for your detail advice.  I completely understand your explain.

But I can't resolve what does "a" stand for there?

a[1,1,1] is 1 * 1 * 1 = 1
a[2,1,1] is 2 * 1 * 1 = 2
a[2,4,2] is 2 * 4 * 2 = 16
a[3,4,2] is 3 * 4 * 2 = 24

?


B.R.
Stephen L







----- Original Message ----
From: Daniel Nordlund <djnordlund at frontier.com>
To: r-help at r-project.org
Sent: Fri, November 5, 2010 11:54:15 PM
Subject: Re: [R] About 5.1 Arrays
Stephen,

Start with a vector of length = 12.  The vector, v, is stored in consecutive 
locations in memory, one after the other.  And
[1]  1  2  3  4  5  6  7  8  9 10 11 12

Now change then change the dimension of v to c(3,4), i.e. a matrix with 3 rows 
and 4 columns.
[,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

The values of v are still stored in memory in consecutive locations.  But now 
you refer to the first location as v[1,1], the second as v[2,1], third as v[3,1] 
... and the 12th as v[3,4].  We sometimes talk about the values "going into" 
v[1,1] or more generally, v[i,j], but the values aren't going anywhere.  They 
are still stored in consecutive locations.  We are just changing how they are 
referred to when we change the dimensions.

So in the 2-dimensional matrix above, the values of the vector v "go into" the 
matrix in column order, i.e. the first column is filled first, then the second, 
...  


Now, create a 24 element vector.
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Change the dimensions to a 3-dimensional array.
, , 1

     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

, , 2

     [,1] [,2] [,3] [,4]
[1,]   13   16   19   22
[2,]   14   17   20   23
[3,]   15   18   21   24

You can visualize a 3-dimensional array as a series of 2-dimensional arrays 
stacked on top of each other.  But this is just a convenient image.  The items 
are still stored consecutively in memory.  Notice that layer one in the stack 
was "filled" first, and the first layer was "filled" just like the previous 
2-dimensional example.  But the items are still physically stored linearly, in 
consecutive locations in memory.

Hope this is helpful,

Dan

Daniel Nordlund
Bothell, WA USA


______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.