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
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).
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.
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.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With