Home > Mobile >  What is the data type by which R indexes arrays?
What is the data type by which R indexes arrays?

Time:12-18

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)]

CodePudding user response:

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

     [,1] [,2] [,3]
[1,]    1    7   13
[2,]    2    8   14

CodePudding user response:

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)
  •  Tags:  
  • r
  • Related