How to Extract a Column from R DataFrame to a List ?
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 the student dataframe. Similarly, we will pass these two vectors to the list and display them.
Syntax:
list(col1, col2,… ,col n)
Example:
R
names= c ( "bobby" , "pinkey" , "rohith" , "gnanu" )
marks= c (78,90,100,100)
student= data.frame (names,marks)
print (student)
print ( "----------------" )
student_list= list (names,marks)
print (student_list)
|
Output:
Method 2: Using $
$ operator in R is used to extract a specific part of data or access a variable in a dataset. 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
names= c ( "bobby" , "pinkey" , "rohith" , "gnanu" )
marks= c (78,90,100,100)
student= data.frame (names,marks)
print (student)
print ( "----------------" )
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
names= c ( "bobby" , "pinkey" , "rohith" , "gnanu" )
marks= c (78,90,100,100)
student= data.frame (names,marks)
print (student)
print ( "----------------" )
a= list (student$names,student$marks)
print (a)
|
Output:
Example :
R
example_list <- list (P = 1:8,
Q = letters [1:8],
R = 5)
example_list
example_list$Q
|
Output :
We can extract elements from a specific column in a list.
Last Updated :
15 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...