反向cbind()函数R.

cur*_*ure 3 r matrix cbind

假设我有一个矩阵列表:

matrix <- matrix(1:4, nrow = 2, ncol = 2)
list <- list(matrix, matrix, matrix)
Run Code Online (Sandbox Code Playgroud)

以及由函数创建的矩阵cbind():

long.matrix <- do.call(cbind, list)

      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    3    1    3    1    3
[2,]    2    4    2    4    2    4
Run Code Online (Sandbox Code Playgroud)

我想颠倒过程来从中得到list矩阵long.matrix.

我可以用for循环手动完成,但我正在寻找类似的东西:function(long.matrix, 3)我认为应该存在.有这样的事吗?

Mat*_*erg 5

蛮力解决方案:

f <- function(long.matrix, num)
           lapply(split(long.matrix, 
                        rep(seq(num), each=(ncol(long.matrix)/num)*nrow(long.matrix))), 
                  function(x) matrix(x, nrow=nrow(long.matrix))
           )

f(long.matrix, 3)
## $`1`
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $`2`
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## $`3`
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
Run Code Online (Sandbox Code Playgroud)

repsplit为分割数据构建类别.由于R是列专业,这里我们采用前四个,第二个四个,第三个四个条目.

在你的榜样当前尺寸的值填充long.matrix3,功能减少到这一点:

lapply(split(long.matrix, rep(seq(3), each=4)), function(x) matrix(x, nrow=2))
Run Code Online (Sandbox Code Playgroud)

注意:

(r <- rep(seq(3), each=4) )
## [1] 1 1 1 1 2 2 2 2 3 3 3 3
split(long.matrix, r)
## $`1`
## [1] 1 2 3 4
## 
## $`2`
## [1] 1 2 3 4
## 
## $`3`
## [1] 1 2 3 4
Run Code Online (Sandbox Code Playgroud)

然后传递其中的每一个matrix以获得所需的格式.