Reputation: 1417
I was trying out something in R when I noticed this. I initialize a 3D array with zeroes, and then use an out-of-range first index for assignment operation.
arr = array(0, c(22, 246, 2))
arr[3463] = 0.15
Now I can also access this value using arr[9, 158, 1]
.
arr[3463] == arr[9, 158, 1]
returns TRUE
How is the out-of-range first index (3463
) being mapped to the 3 indices (9, 158, 1
)?
Upvotes: 0
Views: 861
Reputation: 31181
An array is no more than a vector with attributes as dimensions. The total length of your array is thus 22*246*2 = 10824
and 3463
is not ouf of index in arr
.
Now to understand why there is this mapping arr[3463] == arr[9, 158, 1]
, it's simple arithmetic: 3463 = 157*22+9
.
Values taken in the array with an index (such that 3463
) are taken with the most left dimension. So you start with the first matrix of 22*246
elements, on the first column and you read row per row. You read thus all data (22
). Then you go to the second column and read all rows (at this stage you read 44
data). And so on.
You finally arrive on row 9
of column 158
of the first matrix.
Upvotes: 2
Reputation: 132999
An array is just a vector with a dimension attribute. Thus, you can also use vector subset assigning with it. This is easier to see with a 2-dimensional array a.k.a. a matrix:
m <- matrix(1:16, 4)
dput(m)
#structure(1:16, .Dim = c(4L, 4L))
m[7] <- 0
m
# [,1] [,2] [,3] [,4]
#[1,] 1 5 9 13
#[2,] 2 6 10 14
#[3,] 3 0 11 15
#[4,] 4 8 12 16
Note how the seventh value in the vector was changed.
Upvotes: 4