Home > Blockchain >  Turn list of lists into dataframe in most efficient way in R
Turn list of lists into dataframe in most efficient way in R

Time:09-22

I want to turn a list of lists into a dataframe where each name(listoflists) is a different column name. It is a VERY big list so I want to do this in the most efficient way possible.

listoflists=list(c(1,2,3,4),c(5,6,7,8))
names(listoflists) <- c("col1", "col2")

What could I do to get the following results:

 print(df)
 col1     col2
  1        5
  2        6
  3        7
  4        8
 

CodePudding user response:

We can wrap with data.frame

data.frame(listoflists)

-output

   col1 col2
1    1    5
2    2    6
3    3    7
4    4    8

In case the OP meant, it as a nested list, then unlist the inner list element by looping over the lapply and wrap with data.frame

data.frame(lapply(listoflists, unlist))

If it should be most efficient way, then setDT can be applied as well

library(data.table)
setDT(listoflists)

-output

> listoflists
   col1 col2
1:    1    5
2:    2    6
3:    3    7
4:    4    8

CodePudding user response:

library(dplyr)

bind_rows(listoflists)

# A tibble: 4 x 2
   col1  col2
  <dbl> <dbl>
1     1     5
2     2     6
3     3     7
4     4     8
  •  Tags:  
  • r
  • Related