I have a 3d array in R, say the dimension is 500*3*5, call it data. So there are 5 slices of matrices, each has 500 rows and 3 columns. Now I want to create a new matrix that stacks the 5 slices vertically. So the output has 500*5 rows and 5 columns and it looks like this:
[dim1] [ dim3 ] [1] [2] [3]
1 1 data data data
1 2 data data data
1 3 data data data
1 4 data data data
1 5 data data data
2
2
2
..
500 1 data data data
500 2 data data data
500 3 data data data
500 4 data data data
500 5 data data data
So for each 500 rows, repeat the 2nd and 3rd dimension of the original array, such that column1 repeats the original row index, column2 repeats the old z dimensional index and column 3-5 are the 3 columns of data (numeric and have missing values). i just used the number 5 here, in my data the number is much bigger, so i need to be able to do this more generally. Thanks!!!
Let a
be your 3d array, you can do:
n <- dim(a)
b <- aperm(a, c(3,1,2))
dim(b) <- c(n[3] * n[1], n[2])
If you want to add the dim indices to the left, you can do:
b <- cbind(rev(expand.grid(dim3 = 1:n[3], dim1 = 1:n[1])), b)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments