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:
# 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 $
$ 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:
# 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:
# 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:
Example :
# Creating a list example_list <- list (P = 1:8,
Q = letters [1:8],
R = 5)
example_list # Extracting the values of Q only using $ operator example_list$Q |
Output :
We can extract elements from a specific column in a list.