按行重塑矩阵 [英] Reshape matrix by rows

查看:64
本文介绍了按行重塑矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个尺寸为18000 x 54的矩阵.我想将其重塑为尺寸为54000 x 18的矩阵,其中我的初始矩阵的每一行都变成一个具有3行的矩阵.

I have a matrix with size 18000 x 54. I would like to reshape it as a matrix with size 54000 x 18, in which each row of my initial matrix becomes a matrix which has 3 rows.

让我们举个例子.我有一个矩阵如下:

Let's take an example. I have a matrix as follow:

a = matrix(1:18, nrow = 2, ncol = 9, byrow = T)
a
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
   1    2    3    4    5    6    7    8    9
  10   11   12   13   14   15   16   17   18

我想重塑此矩阵,使其变为:

I would like to reshape this matrix so that it becomes:

[,1]  [,2]  [,3]    
  1      4    7  
  2      5    8
  3      6    9
  10    13   16
  11    14   17
  12    15   18 

我尝试了以下两种方法,但是它们不起作用.第一个如下:

I tried two following ways, but they do not work. The first is as follows:

dim(a) = c(6,3)

第二个是创建一个函数,然后将其应用于每一行:

The second one is to create a function and then apply to each row:

reshapeX = function(x){
   dim(x) = c(3,as.integer(length(x)/3))
   return(as.matrix(x))
}
rbind(apply(a, 1, reshapeX))

但是它也不起作用.有人可以帮忙吗?

But it does not work neither. Can someone help please?

推荐答案

您可以这样做:

do.call(rbind, lapply(1:nrow(a), function(i) matrix(a[i, ], nrow=3)))

包含您的数据:

a <- matrix(1:18, nrow = 2, ncol = 9, byrow = TRUE)
do.call(rbind, lapply(1:nrow(a), function(i) matrix(a[i, ], nrow=3)))
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9
# [4,]   10   13   16
# [5,]   11   14   17
# [6,]   12   15   18

这篇关于按行重塑矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆