0

I have the exact opposite problem to this question...

I essentially have a matrix, and want to create a list out of it, so that I have one element per row, and a subelement for each of the cells.

The names of the elements should be the row names.

So opposite to the question above, starting from a matrix like:

      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5 

I want to obtain a list like the following:

[[1]]
[1] 1 1 2 3 4 5

[[2]]
[1] 2 1 2 3 4 5

[[3]]
[1] 3 1 2 3 4 5

[[4]]
[1] 4 1 2 3 4 5

[[5]]
[1] 5 1 2 3 4 5

[[6]]
[1] 6 1 2 3 4 5

[[7]]
[1] 7 1 2 3 4 5

[[8]]
[1] 8 1 2 3 4 5

[[9]]
[1] 9 1 2 3 4 5

[[10]]
[1] 10  1  2  3  4  5
DaniCee
  • 2,397
  • 6
  • 36
  • 59

2 Answers2

4

Recent versions of R have a function just for this task (splitting by rows or columns):

m <- cbind(1:10, matrix(1:5, nrow = 10, ncol = 5, byrow = TRUE))
colnames(m) <- paste0("V", 1:6)

asplit(m, 1)
#[[1]]
#V1 V2 V3 V4 V5 V6 
# 1  1  2  3  4  5 
#
#[[2]]
#V1 V2 V3 V4 V5 V6 
# 2  1  2  3  4  5 
#
#...
Roland
  • 127,288
  • 10
  • 191
  • 288
3

We can split based on row of matrix.

split(mat, row(mat))

#$`1`
#[1] 1 1 2 3 4 5

#$`2`
#[1] 2 1 2 3 4 5

#$`3`
#[1] 3 1 2 3 4 5

#$`4`
#[1] 4 1 2 3 4 5
#...

data

mat <- matrix(c(1:10, rep(1:5, each = 10)), ncol = 6)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Yep this is it! – DaniCee Oct 08 '19 at 06:19
  • Adjacent question if you don't mind... how could I rename the subelements of every element in the list, so that they are named `c('v1','v2','v3','v4','v5','v6')` for example? – DaniCee Oct 08 '19 at 06:21
  • `setNames(split(mat, row(mat)), paste0("v", 1:nrow(mat)))` – Ronak Shah Oct 08 '19 at 06:22
  • @DaniCee ohh..If you mean elements inside each list, I guess you need to assign them manually again by `lapply(split(mat, row(mat)), function(x) setNames(x, paste0("v", seq_along(x))))` – Ronak Shah Oct 08 '19 at 06:29