How to Convert a List to a dataframe in R
as_tibble
as.data.frame
R Function
List data structure in R is a useful structure store different data types. In this tutorial, we will learn how to convert a list into a dataframe. Here we will assume that the list has multiple vectors of same size.
Convert a list to a dataframe
Creating a list with vectors of equal sizes
Let us get started by create an example list with two variables of equal length.
list_of_equalsize
## 1 a 1
## 2 b 2
## 3 c 3Note that the examples above can convert when the list have vectors of same size and will not work if they differ in lengths. To illustrate that let us make a list with unequal size vectors.
as.tibble(list_of_equalsize)
list_of_unequals <- list(id = letters[1:4],
col1 = 1:3)
list_of_unequalslist_of_unequals <- list(id = letters[1:4],
col1 = 1:3)list_of_unequals
## $id
## [1] "a" "b" "c" "d"
##
## $col1
## [1] 1 2 3If we try to convert the list with unequal vector size, we would get the following error.
as.data.frame(list_of_unequals)
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 4, 3