Open In App

Convert dataframe column to list in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to convert a dataframe into a list by columns in R Programming language. We will be using as.list() function, this function is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and data frames.

Syntax: as.list( object )

Parameter: Dataframe object in our case

After passing the complete dataframe as an input to the function, nothing much has to be done, the function will responsibly convert each column to a separate list, with column elements as elements of the list.

Example 1:

R




df<-data.frame(c1=c(11:15),
            c2=c(16:20),
            c3=c(5:9),
            c4=c(1:5))
  
print("Sample Dataframe")
print (df)
  
list=as.list(df)
  
print("After Conversion of Dataframe into list")
print(list)


Output:

[1] "Sample Dataframe"
  c1 c2 c3 c4
1 11 16  5  1
2 12 17  6  2
3 13 18  7  3
4 14 19  8  4
5 15 20  9  5
[1] "After Conversion of Dataframe into list"
$c1
[1] 11 12 13 14 15
$c2
[1] 16 17 18 19 20
$c3
[1] 5 6 7 8 9
$c4
[1] 1 2 3 4 5

Example 2:

R




df <- data.frame(sr_num = c(200, 400, 600),
                memory=c(128,256,1024),
                text = c("Geeks", "for", "Geeks"))
  
print("Sample Dataframe")
print (df)
  
list=as.list(df)
  
print("After Conversion of Dataframe into list")
print(list)


Output:

[1] "Sample Dataframe"
  sr_num memory  text
1    200    128 Geeks
2    400    256   for
3    600   1024 Geeks
[1] "After Conversion of Dataframe into list"
$sr_num
[1] 200 400 600
$memory
[1]  128  256 1024
$text
[1] Geeks for   Geeks
Levels: for Geeks


Last Updated : 23 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads