In this article, we will discuss how to Convert Nested Lists to Dataframe in R Programming Language.
It can be done with two methods:
- Convert Nested lists to Data Frame by Column.
- Convert Nested lists to Data Frame by Row.
First, let’s Create a nested list.
Code block
Output:

fig 1: Nested List
Method 1: To convert nested list to Data Frame by column.
Approach:
- Create dataframe using data.frame function with the do.call and cbind.
- cbind is used to bind the lists together by column into data frame.
- do.call is used to bind the cbind and the nested list together as a single argument in the Data frame function.
- Also, store the whole data frame in a variable named data_frame and print the variable.
Code:
R
nested_list <- list(l1 = list(1:5, 5:1 ),
l2 = list(100:105, 105:100 ),
l3 = list(200:205, 205:200 ))
data_frame <- as.data.frame(do.call(cbind, nested_list))
data_frame
|
Output:
l1 l2 l3
1 1, 2, 3, 4, 5 100, 101, 102, 103, 104, 105 200, 201, 202, 203, 204, 205
2 5, 4, 3, 2, 1 105, 104, 103, 102, 101, 100 205, 204, 203, 202, 201, 200
Method 2: To convert nested list to Data Frame by row.
Approach:
- Create dataframe using data.frame function with the do.call and rbind.
- rbind is used to bind the lists together by row into data frame.
- do.call is used to bind the rbind and the nested list together as a single argument in the Data frame function.
- Also, store the whole data frame in a variable named data_frame and print the variable.
Code:
R
nested_list <- list(l1 = list(1:5, 5:1 ),
l2 = list(100:105, 105:100 ),
l3 = list(200:205, 205:200 ))
nested_list
data_frame <- as.data.frame(do.call(rbind, nested_list))
data_frame
|
Output:
V1 V2
l1 1, 2, 3, 4, 5 5, 4, 3, 2, 1
l2 100, 101, 102, 103, 104, 105 105, 104, 103, 102, 101, 100
l3 200, 201, 202, 203, 204, 205 205, 204, 203, 202, 201, 200
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
15 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...