Open In App

Convert CSV to list in R

Last Updated : 16 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to convert the content of the CSV file to list in R Programming Language.

CSV Used:

Method 1 : Using for loop

In this method, the file is first read into the R program and then one by one using for loop the columns are extracted and converted to list explicitly using list() function.

Example :

R




df=read.csv("item.csv")  
lst1=list()  
  
for(i in 1:ncol(df)) {      
  lst1[[i]] <- df[ , i]    
}
  
names(lst1)=colnames(df)  
print(lst1)  


Output :

Method 2 : Extracting columns separately and pass to list( ) function

In this method, the file is first read and then each column is extracted one by one explicitly with the name of the column. Then using the list method, all the extracted columns are converted to a list using list() in one go. Here names of the extracted columns is given as comma-separated values to list() to get the required functionality.

Example :

R




df=read.csv('item.csv')
  
a=df$id
b=df$item
c=df$quantity
d=df$price
e=df$bought
f=df$forenoon
g=df$afternoon
h=df$X
  
lst=list(a,b,c,d,e,f,g,h)
  
names(lst)=colnames(df)
  
print(lst)


Output :



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads