Search code examples
rarrayssub-arrayarray-indexing

Sub-array using $p$ commas


Say I have an array Y of size (n x m_1 x m_2 x m_3). If I want the first sub-array of size (m_1 x m_2 x m_3) I can choose it using commas as

Y(1,,,)

Similarly, if Y is of size (n x m_1 x m_2 x m_3 x m_4) and I want the first sub-array of size (m_1 x m_2 x m_3 x m_4), I can choose it using commas as

Y(1,,,,)

In general, if Y is an array of size (n x m_1 x m_2 x ... x m_p) and I want the first sub-array of size (m_1 x m_2 x ... x m_p), I can choose it as

Y(1,,...,)

where ,,..., means p different commas. If p is known, how can I write the p commas?

A simple solution is

array(array(Y,c(dim(Y)[1],prod(dim(Y)[-1])))[1,])

However, this is inefficient code (Y is potentially massive, and I prefer not to transform it to a matrix to then transform it back to an array)


Solution

  • You can always build an expression as text and evaluate it later. In your case, you can use strrep(",", p) to repeat "," p times, then use str2expression() to transform it into an expression that can be evaluated. If you put it in a function:

    slice_first_dimension <- function(arr){
      p <- length(dim(Y))
      eval(str2expression(paste0("arr[1",strrep(",", p-1),"]")))
    }
    
    Y <- array(1:8, dim=c(2,2,2))
    slice_first_dimension(Y)
    #>      [,1] [,2]
    #> [1,]    1    5
    #> [2,]    3    7