Niroshan
Niroshan

Reputation: 2064

Iterating a 2D matrix in chunks using R

I want to iterate the following matrix and print sets of 2 cell values. Is there a way to do this without a for-loop?

Input:

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

Expected Output:

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

This my code:

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

Upvotes: 1

Views: 41

Answers (1)

akrun
akrun

Reputation: 887501

We can get the transpose of the matrix, then convert back to matrix by specifying the ncol

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

Upvotes: 2

Related Questions