Let's assume we've a 3-dimensional array like
a <- array(1:24, dim = c(4, 3, 2))
Accessing or indexing an array is usually done via
# fixing the third (=last) dimension and output the corresponding values of the first and second dimension
a[, , 1]
> a
, , 1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
In this example, I know the number of dimensions is three. So, I can manually type two commas followed by a number for the last dimension (here 1). But now I want to create an expression for dynamically indexing an array by fixing the last dimension a priori not knowing the number of dimensions. This construct should later be used within a loop e.g. lapply().
dims <- paste0(paste0(rep("", length(dim(a)) - 1L), collapse = ","), ",idx")
> dims
[1] ",,idx"
Am I able to convert this dynamically created string ",,idx" into whatever - I know that indexing by itself isn't strongly an expression, that can be used for indexing?
a[dims] <- ... # won't work!
Thanks in advance!