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