Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to split a dataframe 's columns into seperate lists in R

I would like to split a dataframe so that each column is its own lists.

So if we take the iris data set, it will produce a list with an outcome similiar to the below code (however I did this manually).

Ideally looking for a way to use base::split() or purrr::map() to pass a dataframe and then split it vertically across each named column.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# desired outcome

list(
iris$Sepal.Length
,iris$Sepal.Width
,iris$Petal.Length
,iris$Petal.Width
,iris$Species
)

>Solution :

A data.frame is already a list with that structure. The only difference might be that the columns are named in a data.frame and there both the dim, class, an row.names attributes. RonakShah has offered a first pass at probably the most efficient solution since as.list will strip the "class" and "row.names" attributes and the dimension from an existing list, but it will not complete the paring down to your stated goal since the "names" attribute will not be removed. For that you would also need:

unname(as.list(head(iris)))   # working with the first six rows to preserve space
#------------------------------
[[1]]
[1] 5.1 4.9 4.7 4.6 5.0 5.4

[[2]]
[1] 3.5 3.0 3.2 3.1 3.6 3.9

[[3]]
[1] 1.4 1.4 1.3 1.5 1.4 1.7

[[4]]
[1] 0.2 0.2 0.2 0.2 0.2 0.4

[[5]]
[1] setosa setosa setosa setosa setosa setosa
Levels: setosa versicolor virginica

I must scratch my head as to the reason for this effort. I cannot think of any valid reason to discard those attributes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading