How to create data frame using nested list elements in R?

R ProgrammingServer Side ProgrammingProgramming

To create data frame using nested list elements, we would need to unlist the list elements and store them in a matrix then read as a data frame using data.frame function. For example, if we have a nested called LIST then the data frame can be created by using the command −

data.frame(matrix(unlist(LIST),ncol=”No of columns we want”,byrow=F))

Check out the below example to understand how it works.

Example

 Live Demo

nestedList<-list(list(x1=rpois(20,2),x2=rpois(20,2)),list(y1=rpois(20,2),y2=rpois(20,2)))
nestedList

Output

[[1]]
[[1]]$x1
 [1] 1 1 4 5 1 2 1 0 1 1 0 3 2 3 0 2 3 2 1 2

[[1]]$x2
 [1] 2 4 0 2 2 2 1 0 3 1 3 1 2 2 2 3 3 4 3 0

[[2]]
[[2]]$y1
 [1] 1 0 1 2 3 1 2 2 2 2 3 2 3 3 4 3 3 2 3 4

[[2]]$y2
 [1] 0 1 3 2 1 0 2 2 5 2 1 0 1 4 0 1 1 3 1 1

data.frame(matrix(unlist(nestedList),ncol=2,byrow=F))

   X1 X2
1  1  1
2  1  0
3  4  1
4  5  2
5  1  3
6  2  1
7  1  2
8  0  2
9  1  2
10 1  2
11 0  3
12 3  2
13 2  3
14 3  3
15 0  4
16 2  3
17 3  3
18 2  2
19 1  3
20 2  4
21 2  0
22 4  1
23 0  3
24 2  2
25 2  1
26 2  0
27 1  2
28 0  2
29 3  5
30 1  2
31 3  1
32 1  0
33 2  1
34 2  4
35 2  0
36 3  1
37 3  1
38 4  3
39 3  1
40 0  1
raja
Published on 06-Mar-2021 11:44:45
Advertisements