Search code examples
rmatrixdimensionssubmatrix

How to extract dimension of a submatrix from a bigger matrix using R?


I have the following matrix:

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    0    0    0    0    0    0    0     0
 [2,]    0    0    0    0    0    0    0    0    0     0
 [3,]    0    0    0    0    0    0    0    0    0     0
 [4,]    1    1    1    1    0    0    0    0    0     0
 [5,]    1    1    1    1    0    0    0    0    0     0
 [6,]    1    1    1    1    0    0    0    0    0     0
 [7,]    1    1    1    1    0    0    0    0    0     0
 [8,]    1    1    1    1    0    0    0    0    0     0
 [9,]    1    1    1    1    0    0    0    0    0     0
[10,]    1    1    1    1    0    0    0    0    0     0

and I would like to know how to extract the 7x4 dimension of the submatrix with elements equal to 1.


Solution

  • Similar to JDLs answer, but giving you the sub matrix dimensions directly:

    mat <- structure(c(
    0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L
    ), .Dim = c(10L, 10L), .Dimnames = list(NULL, NULL))
    
    dim(mat[apply(mat, 1, any), apply(mat, 2, any)])
    #[1] 7 4
    

    This will remove rows and columns containing only zeros. If you want to keep rows and columns containing at least one 1, you could do:

    mat[3, 5] <- 2 #just to complicate it a little
    
    f <- function(x) any(x==1) #create a simple function
    
    dim(mat[apply(mat, 1, f), apply(mat, 2, f)])
    #[1] 7 4