Home > Software engineering >  Split a matrix into a list while preserving rownames
Split a matrix into a list while preserving rownames

Time:09-27

I have a matrix that has rownames:

mat1.data <- c(1,2,3,4,5,6)
mat1 <- matrix(mat1.data,nrow=3,ncol=2,byrow=TRUE)
rownames(mat1) <- c("a", "b", "c")
colnames(mat1) <- c("t1", "t2")

Expected outcome

$t1
a b c     #I need to preserve rownames
1 3 5

$t2
a b c
2 4 6

How do I do that?

CodePudding user response:

Use asplit with MARGIN = 2 to split column-wise:

asplit(mat1, 2)

output

$t1
a b c 
1 3 5 

$t2
a b c 
2 4 6 
  • Related