Reputation: 959
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
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