ClementWalter
ClementWalter

Reputation: 5272

Split a matrix into submatrices by rownames

Basically I'm wondering if there is any way to make the split function return matrices with same dimnames when used onto a matrix. Here is a MWE:

m <- matrix(1:9, 3, 3, dimnames = list(c('a', 'a', 'b'), LETTERS[1:3]))
ms <- split(a, f = rownames(a))
ms$a
[1] 1 2 4 5 7 8

while I want ms$a to be a matrix like:

matrix(ms$a, ncol = 3, dimnames = list(c('a'), LETTERS[1:3]))
  A B C
a 1 4 7
a 2 5 8

Upvotes: 0

Views: 793

Answers (1)

akrun
akrun

Reputation: 887048

We can split the sequence of rows by the row names and then subset the rows of the matrix using the index.

lapply(split(1:nrow(m), rownames(m)), function(i) m[i,]) 

Upvotes: 3

Related Questions