Reputation: 1683
If I had a matrix like:
[,1] [,2]
[1,] 1 7
[2,] 2 8
[3,] 3 9
[4,] 4 10
[5,] 5 11
[6,] 6 12
Does anyone have an idea as to how I might create a new matrix from the above that looks like:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 7 3 9 5 11
[2,] 2 8 4 10 6 12
Upvotes: 2
Views: 83
Reputation: 23788
Here' another option: First the matrix is transformed into one with two rows, then the odd and even numbered columns are rearranged:
m3 <- m2 <- matrix(c(m),nrow = 2) #take data from original matrix, convert it into a matrix with two rows and store a copy in m2 and m3
m3[,seq(1,ncol(m2),2)] <- m2[,1:(ncol(m2)/2)] #define the odd-numbered columns of m3
m3[,seq(2,ncol(m2),2)] <- m2[,(ncol(m2)/2+1):ncol(m2)] # same for the even-numbered columns
> m3
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 7 3 9 5 11
#[2,] 2 8 4 10 6 12
Upvotes: 2
Reputation: 887108
We create a grouping variable with ?gl
and use the arguments n=nrow(m1)
, k=2
and length=nrow(m1)
. We split
the matrix ('m1'), unlist
, and create a new matrix
with nrow=2
.
matrix(unlist(split(m1,as.numeric(gl(nrow(m1), 2, nrow(m1))))),nrow=2)
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 7 3 9 5 11
#[2,] 2 8 4 10 6 12
Or another option is converting to array
by specifying the dimensions. Here I used c(2, 2, 3)
as we can get a 2x2 matrix for the first two dimensions and the third is based on the nrow(m1)/2
. Then, we can permute the dimensions of the array
using aperm
, concatenate (c
) to form a vector
and convert to matrix
.
matrix(c(aperm(array(t(m1), c(2, 2,3)),c(2,1,3))), nrow=2)
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 7 3 9 5 11
#[2,] 2 8 4 10 6 12
m1 <- structure(1:12, .Dim = c(6L, 2L))
Upvotes: 7