2016-02-03 39 views
1

我想迭代以下矩陣並打印2個單元值的集合。有沒有辦法做到這一點,沒有for循環?使用R對區塊​​中的2D矩陣進行迭代使用R

輸入:

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

預期輸出:

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

這是我的代碼:

mat<-matrix(data=seq(1:18), nrow=3,ncol=6) 
r <- rep(seq(1,3),each=2) 
c1 <- seq(1,6,2) 
c2 <- seq(2,6,2) 

m <- mat[r,c(c1:c2)] # This does not work, it only output first two cells 

回答

2

我們可以得到矩陣的轉置,然後通過指定轉換回matrixncol

matrix(t(mat), ncol=2, byrow=TRUE) 
#  [,1] [,2] 
# [1,] 1 4 
# [2,] 7 10 
# [3,] 13 16 
# [4,] 2 5 
# [5,] 8 11 
# [6,] 14 17 
# [7,] 3 6 
# [8,] 9 12 
# [9,] 15 18