vendredi 31 juillet 2015

R: Fill multidimensional array by row

Before presenting the question, I will point out that something similar was asked here but that this thread doesn't really answer my question.

Consider the following dimensional arrays:

 1D: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
 2D: [[1,2,3,4,5,6,7,8], [9,10,11,12,13,14,15,16]]
 3D: [[[1,2,3,4],[5,6,7,8]], [[9,10,11,12],[13,14,15,16]]]
 4D: [[[[1,2],[3,4]], [[5,6],[7,8]], [[[9,10],[11,12]], [[13,14],[15,16]]]]
 ...

  • The 1D array is length 16
  • The 2D array is 2x8
  • The 3D array is 2x2x4
  • The 4D array is 2x2x2x2

Suppose I want to create the arrays. For the first two, I could do something like this in R

oneD <- array(1:16, dim=16) # class(oneD) = array
twoD <- array(1:16, dim=8) # class(twoD) = matrix

However, the twoD array is now represented as

[[1,3,5,7,9,11,13,15], [2,4,6,8,10,12,14,16]]

I am aware of two ways around this.

twoD <- aperm(array(1:16, dim=8))
twoD <- matrix(1:16, nrow=2, byrow=TRUE)

However, these methods won't work for filling the 3D and 4D arrays. I fill them below, but I would like them to match my definitions above.

threeD <- array(1:16, dim=c(2,2,4)) # class(threeD) = array
fourD <- array(1:16, dim=c(2,2,4)) # class(fourD) = array

Aucun commentaire:

Enregistrer un commentaire