How to convert a list to a dataframe

In this tutorial, we will learn 3 different ways to convert a list object into a dataframe in R. First we will show how to use the base R function as.data.frame() to convert a list to a dataframe. Then we will show examples using map_df() function in purrr package in tidyverse and bind_rows() function in dplyr.

library(tidyverse)

First, let us create a small list object using list() function.

mylist <- list(
  x = letters[1:5],
  y = 3:7, 
  z = LETTERS[6:10]
) 

Our list looks like this

mylist

$x
[1] "a" "b" "c" "d" "e"

$y
[1] 3 4 5 6 7

$z
[1] "F" "G" "H" "I" "J"

Convert a list to a dataframe with as.data.frame()

as.data.frame(mylist)

  x y z
1 a 3 F
2 b 4 G
3 c 5 H
4 d 6 I
5 e 7 J

Convert a list to a dataframe using map_df in purrr

Here is example of using map_df() function in purrr to convert a list to a dataframe.

map_df(mylist, ~.x)

# A tibble: 5 × 3
  x         y z    
  <chr> <int> <chr>
1 a         3 F    
2 b         4 G    
3 c         5 H    
4 d         6 I    
5 e         7 J    

Convert a list to a dataframe with bind_rows

Here is example of using dplyr’s bind_rows() function to convert a list to a dataframe.

bind_rows(mylist)

# A tibble: 5 × 3
  x         y z    
  <chr> <int> <chr>
1 a         3 F    
2 b         4 G    
3 c         5 H    
4 d         6 I    
5 e         7 J    


	
Exit mobile version