2016-06-20 78 views
3

假设我有矩阵列表:逆cbind()返回函数R

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

按功能分类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 

我想扭转过程中得到的list来自long.matrix的矩阵。

我可以用for循环手动执行,但我正在寻找类似于我认为应该存在的内容:function(long.matrix, 3)。有这样的事吗?

+0

非常接近http://stackoverflow.com/questions/37145863/splitting-a-dataframe-into-equal-parts –

回答

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 

rep构建类别split,分裂数据。由于R是专栏,所以我们在这里选取前四名,后四名和三名四名选手。

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

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

注:

(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 

然后每个那些被传递给matrix到获得所需的格式。

+0

谢谢!我明白了:)你认为在R基础上没有实现这样的东西? – cure

+0

@cure我不认为有,但我希望被证明是不正确的。 –

+0

谢谢你的解决方案!污水似乎完整。这就是我找不到直接解决方案的原因。我应该编辑问题,它可能不存在,需要手动完成? – cure

2

这样做:

listm=list() #i=1 
for(i in 1:3)listm[[i]]=long.matrix[,(2*i-1):(i*2)] 

的lapply版本

lapply(1:3,function(ii)long.matrix[,(2*ii-1):(ii*2)]) 

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

我更喜欢使用阵列的尺寸这一点。然后,您可以定义一个split方法矩阵:

split.matrix <- function(x, rslice = 1, cslice = 1) { 
    if (ncol(x) %% cslice) stop("cslice not divisor of number of columns") 
    if (nrow(x) %% rslice) stop("rslice not divisor of number of rows") 

    x <- t(x) 
    dim(x) <- c(dim(x)[1], 
       dim(x)[2]/rslice, 
       rslice) 
    x <- lapply(seq_len(rslice), function(k, a) t(a[,,k]), a = x) 

    if (cslice > 1) { 
    x <- lapply(x, function(y, k) { 

     dim(y) <- c(dim(y)[1], 
        dim(y)[2]/k, 
        k) 
     y <- lapply(seq_len(k), function(k, a) a[,,k], a = y) 
     y 
    }, k = cslice) 
    } 
    if(length(x) == 1L) x <- x[[1]] 

    x 
} 

split(long.matrix, 1, 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 

split(long.matrix, 1, 1) 
#  [,1] [,2] [,3] [,4] [,5] [,6] 
#[1,] 1 3 1 3 1 3 
#[2,] 2 4 2 4 2 4 

split(long.matrix, 2, 1) 

#[[1]] 
#  [,1] [,2] [,3] [,4] [,5] [,6] 
#[1,] 1 3 1 3 1 3 
# 
#[[2]] 
#  [,1] [,2] [,3] [,4] [,5] [,6] 
#[1,] 2 4 2 4 2 4 

split(long.matrix, 2, 3) 
#[[1]] 
#[[1]][[1]] 
#[1] 1 3 
# 
#[[1]][[2]] 
#[1] 1 3 
# 
#[[1]][[3]] 
#[1] 1 3 
# 
# 
#[[2]] 
#[[2]][[1]] 
#[1] 2 4 
# 
#[[2]][[2]] 
#[1] 2 4 
# 
#[[2]][[3]] 
#[1] 2 4