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.
# desired outcome
list(
iris$Sepal.Length
,iris$Sepal.Width
,iris$Petal.Length
,iris$Petal.Width
,iris$Species
)
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 are the dim, class, and 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.