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:

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] 1 2 3 4 5
# 
# $B
# [1] "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

If we want to convert each of the two list elements to a column, we can use a combinations of the cbind, do.call, and as.data.frame R functions:

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:

 

The YouTube video will be added soon.

 

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:

 

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.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top