R_List of the selected matrix rows

I have a matrix, and I want to create a list with the selected rows of this matrix, which are elements of the list.

For example, this is my matrix

my.matrix=matrix(1:100, nrow=20) 

and I want to create a list from this matrix so that each element of this list is part of the matrix and the row index of each part is defined

 my.n=c(1,2,4,3,5,5) 

So the first element of my list should be

 my.matrix[1,] 

second

 my.matrix[2:3,] 

etc.

How to do it in an elegant way?

+4
source share
2 answers

Not really sure, but I think you want something like this ...

 S <- split(seq_len(nrow(my.matrix)), rep.int(seq_along(my.n), my.n)) lapply(S, function(x) my.matrix[x, , drop = FALSE]) 

Here we break the line numbers of my.matrix into my.n . Then we use lapply() over the resulting list S subset of my.matrix with these line numbers.

+3
source
 end <- cumsum(my.n) start <- c(1,(end+1)[-length(end)]) mapply(function(a,b) my.matrix[a:b,,drop=F], start, end) 

mapply takes the first argument of two vectors and applies them to the function. It goes to the second element of each vector and continues through each vector. This behavior works for this application to create a list of subsets as described. credit for @nongkrong for the mapply approach.

+3
source

All Articles