R Arrays
A matrix has two dimensions. An array can have any number: think of a stack of matrices (3 dimensions), or a stack of stacks (4). Like vectors and matrices, an array holds values of a single type.
a <- array(1:24, dim = c(2, 3, 4))
dim(a)
a[, , 1] # the first 2 x 3 "layer"[1] 2 3 4
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
dim = c(2, 3, 4) means 2 rows, 3 columns and 4 layers. Values fill the first dimension fastest, then the second, then the third, so layer 1 holds 1 to 6, layer 2 holds 7 to 12, and so on.
Printing an array
Printing shows each layer separately, with a header like , , 2 meaning "all rows, all columns, layer 2":
small <- array(1:8, dim = c(2, 2, 2))
small, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
Accessing elements
Give one index per dimension. As with matrices, an empty position means "all":
a <- array(1:24, dim = c(2, 3, 4))
a[1, 2, 3] # row 1, column 2, layer 3
a[2, , 4] # row 2 of layer 4
a[, 3, ] # column 3 of every layer
length(a)[1] 15
[1] 20 22 24
[,1] [,2] [,3] [,4]
[1,] 5 11 17 23
[2,] 6 12 18 24
[1] 24
Named dimensions
Arrays are most useful with names on every dimension. Here: temperatures for 2 cities, 3 times of day, over 2 days:
temps <- array(
c(14, 9, 21, 16, 17, 12, 15, 10, 23, 18, 18, 13),
dim = c(2, 3, 2),
dimnames = list(
city = c("Oslo", "Rome"),
time = c("morning", "noon", "evening"),
day = c("Mon", "Tue")
)
)
temps["Rome", "noon", "Tue"]
temps[, , "Mon"][1] 18
time
city morning noon evening
Oslo 14 21 17
Rome 9 16 12
Summaries over dimensions
apply() reduces an array along chosen dimensions. MARGIN = 1 keeps the first dimension, c(1, 3) keeps the first and third:
temps <- array(
c(14, 9, 21, 16, 17, 12, 15, 10, 23, 18, 18, 13),
dim = c(2, 3, 2),
dimnames = list(
city = c("Oslo", "Rome"),
time = c("morning", "noon", "evening"),
day = c("Mon", "Tue")
)
)
apply(temps, "city", mean) # average per city
apply(temps, c("city", "day"), max) # daily maximum per cityOslo Rome
18 13
day
city Mon Tue
Oslo 21 23
Rome 16 18
Oslo is the first city, so its values are the 1st, 3rd, 5th, … elements of the data: 14, 21, 17, 15, 23 and 18, whose mean is 18. Because the first dimension varies fastest when an array is filled, it pays to name the dimensions and check a slice or two after building an array.
Built-in arrays
The datasets package includes some arrays. Titanic is a 4-dimensional table of passengers by class, sex, age and survival:
dim(Titanic)
dimnames(Titanic)$Class
apply(Titanic, c("Class", "Survived"), sum)[1] 4 2 2 2
[1] "1st" "2nd" "3rd" "Crew"
Survived
Class No Yes
1st 122 203
2nd 167 118
3rd 528 178
Crew 673 212
Test yourself
What is dim(array(1:30, dim = c(5, 3, 2)))?
- 30
- 5 3 2
- 2 3 5
- 15 2
In a[i, j, k], what does k select?
- The row
- The column
- The layer (third dimension)
- The type
Which dimension varies fastest when an array is filled from a vector?
- The first
- The last
- The largest
- None, it's random