Reputation: 472
I'm crafting a simulation model, and I think this problem has an easy fix, but I'm just not that used to working with arrays. Let's say I have an array, Array1
, that has 3 dimensions. The first two are of constant and equal length, L
, but the third dimension can be of length from 1 to X at any given time.
I want to be able to periodically subset Array1
to create a second array, Array2
, that is composed of up to the last Y "sheets" of Array1
. In other words, if the length of the third dimension of Array1
is greater than Y, then I want just the last Y sheets of Array1
but, if it's less than Y, I want all sheets of Array1
.
I know that I can crudely pull this off using the tail function and a little finagling:
tmp1 = tail(Array1, (L*L*Y))
Array2 = array(tmp1, dim = (L, L, (L*L/length(tmp1))))
But it seems like there could be a more elegant way of doing this. Is there an equivalent of tail
for arrays in R? Or is there a way that Array2
could be produced via simple logical indexing of Array1
? Or perhaps the apply
function could be used somehow?
Upvotes: 0
Views: 267
Reputation: 57686
Were you after something like this?
a <- array(1:(3*4*5), dim=c(3,4,5))
x <- dim(a)[3]
y <- 2
a[, , seq(to=x, len=min(x, y))]
, , 1
[,1] [,2] [,3] [,4]
[1,] 37 40 43 46
[2,] 38 41 44 47
[3,] 39 42 45 48
, , 2
[,1] [,2] [,3] [,4]
[1,] 49 52 55 58
[2,] 50 53 56 59
[3,] 51 54 57 60
Upvotes: 1