Turn a dataframe into a named list of dataframes with names from a column in R

Viewed 347

So I turned a list into a long dataframe which now has one column, that used to be the names of the list with something like:

df <- map_df(list, ~as.data.frame(.x), .id="id")

Now I want to go the other way round and turn the dataframe back into a named list, based on that column. So for example in the following data:

df = data.frame(a=c("foo", "bar", "baz"), b=1:3)
df
    a b
1 foo 1
2 bar 2
3 baz 3

Now I would like to have a list with the names of column a, so foo bar and baz and the values are the dataframes now only containing one line: 1 for a, 2 for b ...

lst = list(foo=data.frame(b=1), bar=data.frame(bar=2), baz=data.frame(b=3))

3 Answers

You could also use split:

split(df[-1], df[1])

A second option would be using dplyr for grouped variables:

library(dplyr)

df %>% 
  group_split(a, .keep = FALSE)

We can use:

library(tibble)
as.list(deframe(df))
Related