I am trying to split a matrix in the same way that you might split a data.frame using split. Is there a function that does that? For example, I have matrix m and I am trying to split it into a list of matrices using vector g.
m <- matrix(rnorm(50), ncol = 5)
groups <- c('A', 'B', 'C')
g <- sample(groups, 10, replace = T)
split doesn't seem to work with matrices so we could convert it into a data.frame:
split(data.frame(m), f = g)
This works but I'd like to keep it as a matrix. The following loop works:
lapply(groups, function(x) m[g == x,])
But is there a dedicated function, or a better way?