Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R filling array by rows

Tags:

arrays

r

I would like to do some matrix operations and it would be best to utilize 3 (or higher) dimensional arrays. If I want to fill matrices by row there is an argument (byrow = TRUE) however there is no such option for creating/filling a multidimensional array. The only way I've been able to accomplish it is by using aperm to transpose an array that was filled by 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

produces the correct result, a dimension 2,3,2 array that is filled by row. It seems a bit counter intuitive to have to work backward from a Column x Row x Range array to get to a Row x Column x Range array. This might be bad habits from previous f77 coding or have I overlooked something simple?

like image 754
Jim Maas Avatar asked May 01 '14 13:05

Jim Maas


1 Answers

Arrays in R are filled in by traversing the first dimension first. So first the first dimension is traversed, then the second dimension, and then third dimension if it is available.

In 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 assignment:

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 to the 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 assigning to first dimension is more tricky. The following doesn't 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

Data is filled by first traversing the first dimension, then second. What we want is to first traverse the second dimension, then first. So we have to aperm the array (or transpose in case of 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

There are maybe more elegant ways to do the last which I am not aware of.

like image 94
Davor Josipovic Avatar answered Oct 08 '22 11:10

Davor Josipovic