Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Convert dataframe to list of vectors in R

  • Difficulty Level : Basic
  • Last Updated : 25 Aug, 2021

In this article, we will learn how to convert a dataframe into a list of vectors, such that we can use columns of the dataframes as vectors in the R Programming language.

Dataframe columns as a list of vectors

as.list() function in R Language 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

Simply pass our sample dataframe object as an argument in as.list(), which will return a list of vectors. 



Example 1:

R




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

Output:

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

Example 2:

R




df <- data.frame(name = c("Geeks", "for", "Geeks"),
                roll_no = c(10, 20, 30),
                age=c(20,21,22)
                )
 
print("Sample Dataframe")
print (df)
 
print("Our list after being converted from a dataframe: ")
 
list=as.list(df)
list

Output:

[1] "Sample Dataframe"
  name roll_no age
1 Geeks      10  20
2   for      20  21
3 Geeks      30  22
[1] "Our list after being converted from a dataframe: "
$name
[1] Geeks for   Geeks
Levels: for Geeks
$roll_no
[1] 10 20 30
$age
[1] 20 21 22

Dataframe rows as a list of vectors

 split() function in R Language is used to divide a data vector into groups as defined by the factor provided.

Syntax: split(x, f)

Parameters:

  • x: represents data vector or data frame
  • f: represents factor to divide the data

Example:

R




df<-data.frame(c1=c(1:5),
               c2=c(6:10),
               c3=c(11:15),
               c4=c(16:20))
 
print("Sample Dataframe")
print (df)
 
print("Result after conversion")
 
split(df, 1:nrow(df))

Output:

[1] "Sample Dataframe"
  c1 c2 c3 c4
1  1  6 11 16
2  2  7 12 17
3  3  8 13 18
4  4  9 14 19
5  5 10 15 20
[1] "Result after conversion"
$`1`
  c1 c2 c3 c4
1  1  6 11 16
$`2`
  c1 c2 c3 c4
2  2  7 12 17
$`3`
  c1 c2 c3 c4
3  3  8 13 18
$`4`
  c1 c2 c3 c4
4  4  9 14 19
$`5`
  c1 c2 c3 c4
5  5 10 15 20




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!