2

Suppose I have some array, but the dimension is a priori unknown (not necessarily 3, as in the example below).

A=array(1:24, dim=c(2,3,4))

I also have an input vector with length equal to the dimension of this array

pos=c(2,1,3)

Based on this input vector, I want to return

A[1:2,1:1,1:3]

How can I do this automatically? In other words, what kind of data X do I have to pass to A[] so that R understands what I want.

For example, having X be a list does not work:

A[lapply(pos,function(x) 1:x)]
Maël
  • 45,206
  • 3
  • 29
  • 67
axelniemeyer
  • 167
  • 4

2 Answers2

1
pos = lapply(pos, seq)
do.call(`[`, c(list(A), pos))

     [,1] [,2] [,3]
[1,]    1    7   13
[2,]    2    8   14
Maël
  • 45,206
  • 3
  • 29
  • 67
  • 1
    Thanks for your answer. I am looking for something that works independently of the dimension of the array though. – axelniemeyer Dec 17 '21 at 14:42
  • edited! See [here](https://stackoverflow.com/questions/21443086/r-subsetting-n-dimensional-arrays) for more. – Maël Dec 17 '21 at 14:47
0

A function can be created to extract the desired matrix for a given array and vector.

A = array(1:24, dim = c(2,3,4))

pos = c(2,1,3)

array_extractor = function(array, vector) {

   result = array[1:vector[1], 1:vector[2], 1:vector[3]]
   result

}

array_extractor(A, pos)
Cem
  • 108
  • 11