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)
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 usestr2expression()
to transform it into an expression that can be evaluated. If you put it in a function: