rmatrixsplit

Convert matrix to list a of submatrices by row index


I have a matrix m, which I would like to convert into a list l of submatrices consisting of x rows of m.

m <- matrix(sample(15, 60, TRUE), 12)
l <- list(m[1:3,], m[4:6,], m[7:9,], m[10:12,])

I'm certain that there's a simple and more generic solution (full vectorised?) to this, but still being new to R I cannot find it.

I thought about using lapply, but don't really know how.


Solution

  • Just proceed as you did in your question using Map to iterate on the beginning index and finishing index:

    p = 3
    Map(function(u,v) m[u:v,], seq(1,nrow(m),p), seq(p,nrow(m),p))
    
    #[[1]]
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]   14    8    5   10    9
    #[2,]   10    4    5    7    8
    #[3,]    3    3    6    7    3
    
    #[[2]]
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]    4    8   12    1    1
    #[2,]    4    2   13    1   11
    #[3,]    6    2    4    1   12
    
    #[[3]]
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]   11   12    8    5    7
    #[2,]    3    6    2    6    2
    #[3,]   13   13   10    7   12
    
    #[[4]]
    #     [,1] [,2] [,3] [,4] [,5]
    #[1,]    9    7   12    8    9
    #[2,]   10    8   13   14   13
    #[3,]   12    6   11    4   11