Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse to cbind() function R

Tags:

r

matrix

cbind

Suppose I have a list of matrices:

matrix <- matrix(1:4, nrow = 2, ncol = 2)
list <- list(matrix, matrix, matrix)

And a matrix created by function 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

I want to reverse the process to get list of matrices from the long.matrix.

I can do it manually with the for loop, but I am searching for something like: function(long.matrix, 3) which I think should exist. Is there a such thing?

like image 736
cure Avatar asked Mar 11 '26 14:03

cure


1 Answers

Brute-force solution:

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

rep builds the categories for split, to split the data. As R is column-major, here we take the first four, second four, an third four entries.

Filling in the values for the current dimensions of your example long.matrix and 3, the function reduces to this:

lapply(split(long.matrix, rep(seq(3), each=4)), function(x) matrix(x, nrow=2))

Note:

(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

Each of those is then passed to matrix to get the desired format.

like image 166
Matthew Lundberg Avatar answered Mar 13 '26 07:03

Matthew Lundberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!