0

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)

Carlos Llosa
  • 123
  • 6

1 Answers1

1

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
Alexlok
  • 2,999
  • 15
  • 20
  • awesome! This answers my question. Question: what if I want to assign a value to the sub-array? I can't do eval(str2expression(paste0("arr[1",strrep(",", p-1),"]"))) <- array(0,dim(Y)[-1]) – Carlos Llosa Oct 21 '20 at 23:04
  • I'd say either do it in 2 steps (`Y2 <- slice_first_dimension(Y); Y2[xx] <- yy` with appropriate xx and yy), or build an expression that does the transformation, like `my_operation <- paste0("Y[", strrep(xx),"] <- array(yy)"); eval(str2expression(my_operation))` – Alexlok Oct 22 '20 at 16:30
  • I see, this makes a lot of sense. Thank you! – Carlos Llosa Oct 23 '20 at 03:38