You can access the entry \((1, 1, 1)\), i.e. the cell value in first entries of each dimension, in R by:
x[1, 1, 1]
[1] 1
If you want the entries \((i, 1, 1)\) where \(i = 1, 2, 3\) then you can leave the first element blank in R like below:
x[, 1, 1]
[1] 1 2 3
In the above code, the result is a vector but if you wanted to keep the array structure as is then you could add drop = FALSE like below:
x[, 1, 1, drop =FALSE]
, , 1
[,1]
[1,] 1
[2,] 2
[3,] 3
If you want the entries \((1, j, k)\) where \(j = 1, 2\) and \(k = 1, 2, 3, 4\), then you can leave the first two entries in the square bracket like below:
The above function works fine for the arrays x and y. But what if the number of dimension is different?
z <-array(dim =c(2, 2, 2, 2))index_first(z)
Error in x[1, , ]: incorrect number of dimensions
So how do we change our function so it works for an array of any number of dimensions? This is where it gets quite challenging. And while I’m at it, let me throw another challenge.
Challenge 2: assignment
Suppose now I want a function that modifies the entries in the first element of the first dimension by a user supplied value.
, , 1, 1
[,1] [,2]
[1,] 3 3
[2,] NA NA
, , 2, 1
[,1] [,2]
[1,] 3 3
[2,] NA NA
, , 1, 2
[,1] [,2]
[1,] 3 3
[2,] NA NA
, , 2, 2
[,1] [,2]
[1,] 3 3
[2,] NA NA
Practice
So you might wonder when you need such a result. I actually used this for the edibble R-package to create a kind of generalised version of Latin square design, i.e. an array that kind of stitches up multiple Latin squares.
set.seed(1)edibble::latin_array(dim =c(3, 3, 3), nt =3)
Beyond the above, I’m not sure who needs to manipulate arrays with dynamic dimensions. If you have a use case, I’d love to know.
Advanced R Programming unit
The above challenges are sort of challenges that I hope to include in the Advanced R Programming unit that’s planned for Honours level in the Business Analytics major at Monash University. If you want to learn more about R as a programming lanuage (instead of a data analysis tool) then I’d recommend the Advanced R book by Hadley Wickham.