2016-06-20 75 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