Search code examples
rmatrixindexingsubmatrix

Indexing a submatrix in R


Currently in class, I am learning about matrices. There is a particular problem I just can't crack. The problem had me create a matrix such as this:

m=matrix(seq(2,48,2),nrow=6,ncol=4)

Which returns this:

     [,1] [,2] [,3] [,4]
[1,]    2   14   26   38
[2,]    4   16   28   40
[3,]    6   18   30   42
[4,]    8   20   32   44
[5,]   10   22   34   46
[6,]   12   24   36   48

From here, I have to create another matrix using m that will return the following numbers in a matrix: 28,30,36,38,44,46. Ideally returning something like this:

     [,1] [,2]
[1,]   28   38
[2,]   30   44
[3,]   36   46

I've thought about just indexing each number individually, but I am struggling to have R return more than one number. How would I go about doing this? Thank you!


Solution

  • If it is custom values, then index to get the values and convert to matrix

    matrix(m[c(14:15, 18, 19, 22, 23)], ncol=2)
    #      [,1] [,2]
    #[1,]   28   38
    #[2,]   30   44
    #[3,]   36   46