Convert list with varying number of elements into a data frame.

R ProgrammingServer Side ProgrammingProgramming

To convert list with varying number of elements into a data frame in R, we can use stri_list2matrix function of stringi package along with as.data.frame function.

For Example, if we have a list called LIST that contains varying number of elements then we can convert it into a data frame by using the below mentioned command −

as.data.frame(t(stri_list2matrix(LIST)))

Example 1

Following snippet creates a sample list −

List1<-
list(x1=rpois(2,5),x2=rpois(1,3),x3=rpois(2,8),x4=rpois(4,5),x5=rpois(2,2),
x6=rpois(2,1),x7=rpois(3,8),x8=rpois(2,2),x9=rpois(1,5),x10=rpois(4,5))
List1

The following list is created −

$x1  1 3$x2
 1
$x3  8 13$x4
 1 6 4 3
$x5  1 1$x6
 0 1
$x7  7 14 11$x8
 2 3
$x9  6$x10
 2 6 2 4

To load stringi package and convert List1 into a data frame on the above created list, add the following code to the above snippet −

List1<-
list(x1=rpois(2,5),x2=rpois(1,3),x3=rpois(2,8),x4=rpois(4,5),x5=rpois(2,2),
x6=rpois(2,1),x7=rpois(3,8),x8=rpois(2,2),x9=rpois(1,5),x10=rpois(4,5))
library(stringi)
df1<-as.data.frame(t(stri_list2matrix(List1)))
df1

Output

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

V1  V2    V3 V4
1 1   3   <NA <NA
2 1 <NA   <NA <NA
3 8  13   <NA <NA
4 1   6     4 3
5 1   1   <NA <NA
6 0   1   <NA <NA
7 7  14    11 <NA
8 2   3   <NA <NA
9 6 <NA   <NA <NA
10 2   6     2 4

Example 2

Following snippet creates a sample list −

List2<-
list(rnorm(2),rnorm(1),rnorm(3),rnorm(2),rnorm(2),rnorm(1),rnorm(2),rnorm(3),rnorm(2),rnorm(3))
List2

The following list is created −

[]
 -0.03506701 -0.55296351
[]
 0.005158427
[]
 -0.7572075 -0.3224273 1.2230982
[]
 2.515718 0.459838
[]
 0.2281859 1.4827560
[]
 -1.437357
[]
 -0.6724493 -0.8615715
[]
 -0.3267674 0.3821203 1.3682284
[]
 -1.1927376 0.6963071
[]
 -1.8503924 -0.8548566 0.3238128

To convert List2 into a data frame on the above created list, add the following code to the above snippet −

List2<-
list(rnorm(2),rnorm(1),rnorm(3),rnorm(2),rnorm(2),rnorm(1),rnorm(2),rnorm(3),rnorm(2),rnorm(3))
df2<-as.data.frame(t(stri_list2matrix(List2)))
df2

Output

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

V1 V2 V3
1 -0.0350670057960313 -0.552963507178783 <NA
2  0.00515842713500514 <NA <NA
3 -0.7572075156728    -0.32242727820248 1.22309822228101
4 2.51571828926956     0.459838038672105 <NA
5 0.228185881424775    1.48275597834426 <NA
6 -1.4373572339596     <NA <NA
7 -0.672449323899707  -0.861571465667793 <NA
8 -0.326767408109411   0.38212030846509 1.36822838416228
9 -1.19273760057282    0.696307135245131 <NA
10 -1.85039242746415   -0.854856579078842 0.323812773976994