Lisa
Lisa

Reputation: 959

Reshape 2d into 3d matrix with rows as columns and columns as the 3rd dimension

How would I reshape a matrix where I'd need every 2 rows to start a new column and every column to be in the third dimension in R? I haven't really tried anything outside of dim() which obviously didn't work, as I'm having a hard time wrapping my head around this transformation.

What I have:

d h
c g
b f
a e

What I want:

[ , , 1]
b d
a c

[ , , 2]
g h
e f

Upvotes: 0

Views: 67

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

I think you can get the required structure of your matrix adjusting the dim attribute.

I added two additional rows to your matrix, it looks like this :

mat <- structure(c("d", "c", "b", "a", "k", "l", "h", "g", "f", "e", 
"j", "m"), .Dim = c(6L, 2L))
mat

#    [,1] [,2]
#[1,] "d"  "h" 
#[2,] "c"  "g" 
#[3,] "b"  "f" 
#[4,] "a"  "e" 
#[5,] "k"  "j" 
#[6,] "l"  "m" 

To get every column into 3rd dimension and only 2 values in each column you can do :

dim(mat) <- c(2, nrow(mat)/2, ncol(mat))
mat

#, , 1

#     [,1] [,2] [,3]
#[1,] "d"  "b"  "k" 
#[2,] "c"  "a"  "l" 

#, , 2

#     [,1] [,2] [,3]
#[1,] "h"  "f"  "j" 
#[2,] "g"  "e"  "m"  

Upvotes: 2

akrun
akrun

Reputation: 887118

We can use array

 array(t(df1), c(2, 2, 2))

Upvotes: 1

Related Questions