R 基于行创建新列

R 基于行创建新列,r,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 我们用?gl

如果我有一个矩阵,比如:

     [,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

我们用
?gl
创建一个分组变量,并使用参数
n=nrow(m1)
k=2
length=nrow(m1)
。我们
拆分
矩阵('m1'),
取消列表
,并使用
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
或者,另一个选项是通过指定维度转换为
数组
。这里我使用了
c(2,2,3)
,因为我们可以得到前两个维度的2x2矩阵,第三个基于
nrow(m1)/2
。然后,我们可以使用
aperm
来排列
数组的维度,连接(
c
)以形成
向量
,并转换为
矩阵

 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这里有另一个选项:首先将矩阵转换为两行矩阵,然后重新排列奇数和偶数列:

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

m3的逻辑是什么?第1行的奇数行和第2行的偶数行?@Tensibai他们想将矩阵分割成4X4个块,然后cbind它们
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