Split Data Frame into List of Data Frames Based On ID Column in R (Example)

 

In this tutorial, I’ll explain how to separate a large data frame into a list containing multiple data frames in R.

The article looks as follows:

Let’s jump right to the example:

 

Creation of Exemplifying Data

Have a look at the following example data.

data <- data.frame(id = c("A", "A", "B", "B", "B", "C"),  # Example data
                   x1 = 1:6,
                   x2 = 11:16)
data                                                      # Print example data
#   id x1 x2
# 1  A  1 11
# 2  A  2 12
# 3  B  3 13
# 4  B  4 14
# 5  B  5 15
# 6  C  6 16

As you can see based on the previous RStudio console output, our example data contains six rows and three columns. The first variable is an ID-column that we can use to separate our data later on.

 

Example: Splitting Data Frame Based on ID Column Using split() Function

In this Example, I’ll show how to convert our data frame to a list of data frames using the split() function.

data_list <- split(data, f = data$id)                     # Split data
data_list                                                 # Print list
# $A
# id x1 x2
# 1  A  1 11
# 2  A  2 12
# 
# $B
# id x1 x2
# 3  B  3 13
# 4  B  4 14
# 5  B  5 15
# 
# $C
# id x1 x2
# 6  C  6 16

The previous output shows our resulting list object. It contains three list elements and each of these list elements is a subset of our original data frame.

 

Video & Further Resources

Do you need further explanations on the R code of this article? Then you could have a look at the following video of my YouTube channel. I illustrate the R syntax of this article in the video:

 

The YouTube video will be added soon.

 

In addition, you may have a look at the related tutorials on my website:

 

To summarize: In this R tutorial you learned how to split huge data frames into lists. If you have any further questions and/or comments, tell me about it in the comments section. Besides that, please subscribe to my email newsletter to get updates on new articles.

 

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