Bobesh
Bobesh

Reputation: 1207

Split matrix to a list of matrix by vector

I am trying to split my matrix to a list by unique value in vector. Vector will have as many values as is in each column in matrix. Here is an example:

 #matrix
 b <- cbind(c(2,2,1,0), c(2,2,1,5), c(2,2,5,6))
 #vector
 a <- c(5,5,4,1)
 #??
 #my outcome should looks like
 v <- list(cbind(c(2,2), c(2,2), c(2,2)), c(1,1,5), c(0,5,6))

so basically, I want to split my matrix into multiple matrices by rows by unique values in a vector. More specifically, my vector is sorted from highest value to lowest value and I need to keep it in a list! As you can see in the example, v[[1]] is matrix for unique(a)[1] and so on.

Upvotes: 1

Views: 1349

Answers (1)

Roland
Roland

Reputation: 132864

lapply(split(seq_along(a), a), #split indices by a
       function(m, ind) m[ind,], m = b)[order(unique(a))]
#$`5`
#     [,1] [,2] [,3]
#[1,]    2    2    2
#[2,]    2    2    2
#
#$`4`
#[1] 1 1 5
#
#$`1`
#[1] 0 5 6

Upvotes: 2

Related Questions