How to convert matrices stored in a list into vectors in R?


A list may contain vectors, data frames, matrices, lists etc. If a list contains matrices and we want to convert those matrices into vectors then lapply function can be used along with as.vector function.

For example, if we have a list called LIST that contains matrices then we can convert those matrices into data frames by using the below given command −

lapply(LIST,function(x) as.vector(x))

Example

Following snippet creates the matrices −

M1<-matrix(rpois(25,5),ncol=5)
M2<-matrix(rpois(25,5),ncol=5)
M3<-matrix(rpois(40,10),ncol=2)
M4<-matrix(rpois(40,25),ncol=2)
List<-list(M1,M2,M3,M4)
List

The following matrices are created −

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

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

[[3]]
     [,1][,2]
[1,]  13   5
[2,]   4  10
[3,]   6   6
[4,]   7  11
[5,]   8  10
[6,]  18   6
[7,]  10   8
[8,]  14  14
[9,]  10   9
[10,]  9  15
[11,] 10   8
[12,]  9   8
[13,]  8   7
[14,] 14   9
[15,] 11   9
[16,]  9   9
[17,] 14  13
[18,] 10   9
[19,]  7   9
[20,]  8  16

[[4]]
     [,1][,2]
[1,]  24  20
[2,]  26  25
[3,]  23  28
[4,]  22  22
[5,]  23  27
[6,]  31  22
[7,]  33  33
[8,]  31  27
[9,]  19  33
[10,] 25  23
[11,] 25  23
[12,] 33  27
[13,] 26  28
[14,] 25  31
[15,] 26  26
[16,] 25  31
[17,] 22  29
[18,] 28  22
[19,] 22  30
[20,] 30  24

To convert matrices stored in a list into vectors in R, add the following code to the above snippet −

M1<-matrix(rpois(25,5),ncol=5)
M2<-matrix(rpois(25,5),ncol=5)
M3<-matrix(rpois(40,10),ncol=2)
M4<-matrix(rpois(40,25),ncol=2)
List<-list(M1,M2,M3,M4)
lapply(List,function(x) as.vector(x))

Output

If you execute all the above given snippets as a single program, it generates the following output −

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

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

[[3]]
[1] 13 4 6 7 8 18 10 14 10 9 10 9 8 14 11 9 14 10 7 8 5 10 6 11 10
[26] 6 8 14 9 15 8 8 7 9 9 9 13 9 9 16

[[4]]
[1] 24 26 23 22 23 31 33 31 19 25 25 33 26 25 26 25 22 28 22 30 20 25 28 22 27
[26] 22 33 27 33 23 23 27 28 31 26 31 29 22 30 24

Updated on: 23-Nov-2021

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements