The_Tams
The_Tams

Reputation: 225

R: How to bind four dimensional arrays in one array, by a new, fifth dimension

I have multiple four-dimensional arrays, each of which contains one year of data. The dimensions in my real dataset are latitude by longitude coordinates for each matrix, by month, then my percentage in each of 12 categories of observation.

I have made a mini-version for the example

test.array1 <- array(0, dim = c(16, 8, 4, 3), dimnames = list(c(-7.5:7.5), c(-3.5:3.5), c("Jan", "Feb", "Mar", "Apr"), 1:3))
test.array2 <- array(0, dim = c(16, 8, 4, 3), dimnames = list(c(-7.5:7.5), c(-3.5:3.5), c("Jan", "Feb", "Mar", "Apr"), 1:3))
test.array3 <- array(0, dim = c(16, 8, 4, 3), dimnames = list(c(-7.5:7.5), c(-3.5:3.5), c("Jan", "Feb", "Mar", "Apr"), 1:3))

I wish to combine these as a fifth dimension, year, to be of the from this makes

test.array.all <- array(0, dim = c(16, 8, 4, 3, 18), dimnames = list(c(-7.5:7.5), c(-3.5:3.5), c("Jan", "Feb", "Mar", "Apr"), 1:3, 2003:2020))

But I need to make it out of the existing arrays. I want the final array to have dimensions [16, 8, 4, 3, 18]

I tried a few options with abind (using just these three arrays, so aiming at [16 , 8, 4, 3, 3], from the abind package, but I can't figure out how to make its options work to combine them as a new dimension. e.g.

test.array.bind <- abind(test.array1, test.array2, test.array3)

binds the arrays on the last dimensions (the obs) of dimensions [16, 8, 4, 9]

test.array.bind <- abind(c(test.array1, test.array2, test.array3))

makes a one dimensional array, 4608 long.

Upvotes: 0

Views: 361

Answers (1)

The_Tams
The_Tams

Reputation: 225

For some reason, when I was going through the options starting with matrices as per the closest questions I had found in stackoverflow, I could not get 'along' to behave as I thought it should. With the arrays I generated above to write this question, though, it worked fine. I decided it was worth adding the answer here in case it helps anyone else.

test.array.bind <- abind::abind(test.array1, test.array2, test.array3, along = 5)  
# assuming pkg:abind has been installed

with the value for along being the number of dimensions of the existing arrays +1, this produces my desired dimensions of [16, 8, 4, 3, 3]

Upvotes: 1

Related Questions