Skip to content
Related Articles

Related Articles

Improve Article
How to Extract a Column from R DataFrame to a List ?
  • Last Updated : 30 Apr, 2021

In this article, we will discuss how to extract a column from a DataFrame to a List in R Programming Language.

Method 1: Converting all columns to list

In this method, we are going to create a vector with character (names) and integer(marks) type data and passing to student dataframe. Similarly, we will pass these two vectors to list and display them.

Syntax:

list(col1, col2,… ,col n)

Example:



R




# vector with names
names=c("bobby","pinkey","rohith","gnanu")
  
# vector with marks
marks=c(78,90,100,100)
  
# pass these vectors as inputs 
# to the dataframe
student=data.frame(names,marks)
  
print(student)
print("----------------")
  
# pass those vectors to list
student_list=list(names,marks)
print(student_list)

Output:

Method 2: Using $

We can pass data frame column to a list by using $ operator. The columns to be selected are to be passed with dataframe name separated by $.

Syntax:

list(dataframe$column_name)

Example:

R






# vector with names
names=c("bobby","pinkey","rohith","gnanu")
  
# vector with marks
marks=c(78,90,100,100)
  
# pass these vectors as inputs 
# to the dataframe
student=data.frame(names,marks)
print(student)
print("----------------")
  
# pass marks column  to list
print(list(student$marks))

Output:

We can extract more than one column using the same approach and then again pass it to the list() function.

Example:

R




# vector with names
names=c("bobby","pinkey","rohith","gnanu")
  
# vector with marks
marks=c(78,90,100,100)
  
# pass these vectors as inputs
# to the dataframe
student=data.frame(names,marks)
print(student)
print("----------------")
  
# pass all columns  to list
a=list(student$names,student$marks)
print(a)

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :