Create Data Frame where a Column is a List in R (Example)

 

In this tutorial you’ll learn how to construct a new data frame with a list as column in the R programming language.

The content of the article is structured like this:

Let’s dig in:

 

Example: Creating Data Frame Containing Numeric Vector & List

The following R code shows how to construct a new data frame consisting of a numeric column and a list. First, we need to create a numeric vector:

my_var <- 1:3                             # Create vector
my_var                                    # Print vector
# 1 2 3

Then, we also need to create a list:

my_list <- list(1:5, letters[1:3], 5)     # Create list
my_list                                   # Print list
# [[1]]
# [1] 1 2 3 4 5
# 
# [[2]]
# [1] "a" "b" "c"
# 
# [[3]]
# [1] 5

Finally, we can store our numeric vector and our list in a data frame. Note that we have to wrap our list with the I() function to make sure that our list object is retained as it is:

data <- data.frame(my_var, I(my_list))    # Create data.frame
data                                      # Print data.frame
#   my_var      my_list
# 1      1 1, 2, 3,....
# 2      2      a, b, c
# 3      3            5

The previous output may look a bit confusing. However, if you have a look at the variable, in which our list is stored, you can see that the data structure is the same as in the original list:

data$my_list                              # Print list column of data.frame
# [[1]]
# [1] 1 2 3 4 5
# 
# [[2]]
# [1] "a" "b" "c"
# 
# [[3]]
# [1] 5

 

Video & Further Resources

I have recently published a video on my YouTube channel, which explains the contents of the present page. You can find the video below:

 

 

Also, you could have a look at the related posts on my website. A selection of tutorials about data frames and lists is shown here:

 

At this point you should have learned how to use a list as data frame variable in R. Please let me know in the comments, in case you have further questions or comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top