Convert List of Vectors to Data Frame in R (2 Examples)
This tutorial explains how to convert a list of vectors to a data frame in the R programming language.
Table of contents:
- Creating Example Data
- Example 1: Convert List to Data Frame Columns
- Example 2: Convert List to Data Frame Rows
- Video, Further Resources & Summary
Let’s get started!
Creating Example Data
In the following examples, we will use this example list:
my_list <- list(A = 1:5, B = letters[1:5]) # Create example list my_list # $A #  1 2 3 4 5 # # $B #  "a" "b" "c" "d" "e"
As you can see based on the output of the RStudio console, our example list contains two vectors. One of them is numeric and one of them is a character.
Example 1: Convert List to Data Frame Columns
as.data.frame(do.call(cbind, my_list)) # Convert list to data frame columns # A B # 1 1 a # 2 2 b # 3 3 c # 4 4 d # 5 5 e
You can see based on the RStudio console output that each of our list elements was converted to a column.
Note that the list elements need to have the same length.
Example 2: Convert List to Data Frame Rows
We can also use the rbind function instead of cbind in order to convert our example list to a data frame with two rows and five columns (i.e. each value of our list elements is stored in a new column):
as.data.frame(do.call(rbind, my_list)) # Convert list to data frame rows # V1 V2 V3 V4 V5 # A 1 2 3 4 5 # B a b c d e
Video, Further Resources & Summary
Some time ago I have released a video on my YouTube channel, which shows the topics of this article. You can find the video below:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may want to read the related tutorials of https://statisticsglobe.com/. You can find a selection of tutorials about merging, binding and combining lists and data frames below:
- The cbind R Function
- The rbind R Function
- Merge Lists in R
- Combine Lists in R
- Merge Multiple Data Frames in List
- The merge R Function
- Create List of Data Frames in R
- The do.call R Function
- R Functions List (+ Examples)
- The R Programming Language
In this post, I showed how to convert a list to a dataframe with column names in the R programming language. In case you have additional questions, let me know in the comments below.
Statistics Globe Newsletter