Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R 3d array to 2d matrix

Tags:

arrays

r

matrix

Let's assume I have a 3d array of dimensions (x,y,z) and would like to restructure my data as a matrix of dimensions (x*y,z), something like:

my_array <- array(1:600, dim=c(10,5,12))
my_matrix<-data.frame()

for (j in 1:5) {
  for (i in 1:10) {
     my_matrix <- rbind (my_matrix, my_array[i,j,1:12])
 }
}

Could you suggest a faster and more elegant way?

thanks

like image 675
Nemesi Avatar asked Jun 06 '16 16:06

Nemesi


People also ask

How do I turn an array into a matrix in R?

To convert an array into a matrix in R, we can use apply function. For example, if we have an array called ARRAY that contains 2 array elements then we can convert this array into a single matrix using the command apply(ARRAY,2,c).

How to make multidimensional array in R?

Creating a Multidimensional ArrayAn array is created using the array() function. It takes vectors as input and uses the values in the dim parameter to create an array. A multidimensional array can be created by defining the value of 'dim' argument as the number of dimensions that are required.

How do you make a 3D array in R?

Create 3D array using the dim() function in R 3 D array is also known as Multidimensional array. We can create a multidimensional array with dim() function. We can pass this dim as an argument to the array() function.

How many dimensions can an array have in R?

An array in R can have one, two or more dimensions. It is simply a vector which is stored with additional attributes giving the dimensions (attribute "dim" ) and optionally names for those dimensions (attribute "dimnames" ). A two-dimensional array is the same thing as a matrix .


1 Answers

Change the dimension of the array:

dim(my_array) <- c(10 * 5 , 12)
like image 176
Lars Arne Jordanger Avatar answered Oct 30 '22 15:10

Lars Arne Jordanger