R fill array line by line

I would like to do some matrix operations and it would be better to use 3 (or higher) dimensional arrays. If I want to fill matrices row by row, that is, an argument (byrow = TRUE ), but such a possibility for creating / filling a multidimensional array... The only way I was able to do it was using aperm to wrap the array filled with a column. For example:

arr.1 <- array(1:12, c(3,2,2))

arr.1

arr.2 <- aperm(arr.1, c(2,1,3))

arr.2

      

outputs the correct result, size 2,3,2 of the array, which is filled with a string. It seems like a somewhat counter intuitive to work back from the Column x Row x Range array to go to the x Range Row x Column array. Could it be bad habits from the previous f77 coding or am I missing something simple?

+2


source to share


2 answers


My recommendation would be to "teach" yourself the default by doing



foo<- array(1:60,3,4,5)

You can then populate an arbitrary array by rearranging the original vector or by creating matrices and loading them into the z-layers of the array in the order you want.

0


source


Arrays in R are populated with the first first dimension. So, the first dimension is passed first, then the second dimension, and then the third dimension, if available.

In the case of a matrix:

array(c(1,2,3), dim = c(3,3))

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

      

Or with an appointment:

M <- array(dim = c(3,3))
M[,] <- c(1,2,3)
M

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

      

Assigning a second dimension is easy:



M <- array(dim = c(3,3))
M[,2:3] <- c(1,2,3)
M

     [,1] [,2] [,3]
[1,]   NA    1    1
[2,]   NA    2    2
[3,]   NA    3    3

      

But the purpose of the first dimension is more complicated. The following result does not give the expected result:

M <- array(dim = c(3,3))
M[2:3,] <- c(1,2,3)
M

     [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]    1    3    2
[3,]    2    1    3

      

The data is filled with the first intersection of the first dimension, then the second. We want to transfer the second dimension first and then first. Therefore, we have to aperm

array (or transpose in the case of a matrix).

M <- array(dim = c(3,3))
Mt <- aperm(M)
Mt[,2:3] <- c(1,2,3)
M <- aperm(Mt)
M

     [,1] [,2] [,3]
[1,]   NA   NA   NA
[2,]    1    2    3
[3,]    1    2    3

      

Perhaps there are more elegant ways to do the latter, which I am not aware of.

0


source







All Articles