There are many cases in which you might want to convert a list to a data frame in R. This tutorial explains three different ways to do so.
Method 1: Base R
The following code snippet shows how to convert a list to a data frame using only base R:
#create list
my_list #convert list to data frame
data.frame(t(sapply(my_list,c)))
X1 X2 X3 X4 X5
1 a b c d e
2 f g h i j
In this example, sapply converts the list to a matrix, then data.frame converts the matrix to a data frame. The end result is a data frame of two rows and five columns.
Method 2: Data Table
The following code snippet shows how to convert a list of two nested lists into a data frame with two rows and three columns using the rbindlist function from the data.table library:
#load data.table library library(data.table) #create list my_list #convert list to data frame rbindlist(my_list) var1 var2 var3 1: 1 2 3 2: 4 5 6
This results in a data table with two rows and three columns. If you’d like to convert this data table to a data frame, you can simply use as.data.frame(DT).
This method converts a list to a data frame faster than the previous method if you’re working with a very large dataset.
Method 3: Dplyr
The following code snippet shows how to convert a list of two nested lists into a data frame with two rows and three columns using the bind_rows function from the dplyr library:
#load library library(dplyr) #create list my_list #convert list to data frame bind_rows(my_list) # A tibble: 2 x 3 var1 var2 var3 1 1 2 3 2 4 5 6
This results in a data frame with two rows and three columns.
This method also tends to work faster than base R when you’re working with large datasets.