Open In App

Convert dataframe to nested list in R

Improve
Improve
Like Article
Like
Save
Share
Report

In R Programming Data frame is nothing but a two-dimensional entity that consists of rows and columns whereas Lists in R are data structures that are able to store multiple data values at once.

List Creation

Lists in R can be created using list() function.

Syntax: list(element1, element2, element3,….)

Dataframe Creation

Dataframes in R are created using data.frame() function.

Syntax: data.frame(column1=values, column2=values,….)

Conversion of data frame to list

In R programming there is no direct function that converts data frame to list so we need to convert it using loop and code for that is given below.

R




# Creation of sample data frame
df<-data.frame(
  age=c(1,2,3,4,5),
  name=c('a','b','c','d','e')
)
 
nested_list<-list()
for(i in df){
    nested_list<-append(nested_list,list(i))
}
 
# Print data frame
print('Data Frame')
print(df)
 
# Check the type of variable nested_list
print('Type:-')
print(typeof(nested_list))
 
# Print created nested list
print('Nested List')
print(nested_list)


Output:

 

Explanation:

As in R Programming, there are no in-built functions to convert data frame to list, following are the steps to convert

  •  At first we created a sample data frame(df) and an empty list(nested_list) 
  •  Later on by using for loop we accessed columns of data frame and appended it to the created empty list.
  •  To check the type of nested_list variable we used typeof() function in R [Even for a Nested List in R it’s data type is List only so the output returned is of type “List”].
  •  Finally printed the created Nested List.

Last Updated : 11 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads