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.
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 <- list(id = letters[1:3], col1 = 1:3)
Our list looks like this, we have one character variable and one numerical variable.
list_of_equalsize ## $id ## [1] "a" "b" "c" ## ## $col1 ## [1] 1 2 3
List to Dataframe with as.data.frame()
One of the ways to convert a list of equal size to a dataframe is to use as.data.frame() available in base R.
as.data.frame(list_of_equalsize) ## id col1 ## 1 a 1 ## 2 b 2 ## 3 c 3
library(tidyverse)
List to Dataframe with as_tibble()
Another way we can convert a list into a dataframe is to use tidyverse’s as_tibble() function. as_tibble function converts the list into a tibble which is a dataframe like structure available in tidyverse.
as_tibble(list_of_equalsize) ## # A tibble: 3 x 2 ## id col1 ## <chr> <int> ## 1 a 1 ## 2 b 2 ## 3 c 3
Note 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_unequals
list_of_unequals <- list(id = letters[1:4], col1 = 1:3)
list_of_unequals ## $id ## [1] "a" "b" "c" "d" ## ## $col1 ## [1] 1 2 3
If 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