根据行创建新列

时间:2015-08-20 12:34:56

标签: r

如果我有一个矩阵:

     [,1] [,2] 
[1,]    1    7
[2,]    2    8
[3,]    3    9
[4,]    4   10
[5,]    5   11
[6,]    6   12

有没有人知道如何从上面创建一个新的矩阵,如下所示:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    7  3    9    5    11
[2,]    2    8  4    10   6    12

2 个答案:

答案 0 :(得分:7)

我们使用?gl创建分组变量,并使用参数n=nrow(m1)k=2length=nrow(m1)。我们split矩阵('m1'),unlist,并使用matrix创建新的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

或者其他选项是通过指定尺寸转换为array。在这里,我使用了c(2, 2, 3),因为我们可以获得前两个维度的2x2矩阵,第三个矩阵基于nrow(m1)/2。然后,我们可以使用array置换aperm的维度,连接(c)以形成vector并转换为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))

答案 1 :(得分:2)

下面&#39;另一种选择:首先将矩阵转换为具有两行的矩阵,然后重新排列奇数和偶数列:

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
相关问题