How to convert matrices stored in a list into data frames 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 data frames then lapply function can be used along with as.data.frame 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 command −

lapply(LIST,function(x) as.data.frame(x))

Example

Following snippet creates a list of 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

Output

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

Now, to convert the matrices stored in list to data frames, 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.data.frame(x))

Output

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

[[1]]
   V1 V2 V3 V4 V5
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]]
  V1 V2 V3 V4 V5
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]]
   V1  V2
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]]
   V1  V2
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

Updated on: 05-Nov-2021

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements