2

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))

Lenn
  • 1,283
  • 7
  • 20

3 Answers3

3

You could also use split:

split(df[-1], df[1])
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

A second option would be using dplyr for grouped variables:

library(dplyr)

df %>% 
  group_split(a, .keep = FALSE)
zx8754
  • 52,746
  • 12
  • 114
  • 209
DPH
  • 4,244
  • 1
  • 8
  • 18
1

We can use:

library(tibble)
as.list(deframe(df))
Elletlar
  • 3,136
  • 7
  • 32
  • 38
akrun
  • 874,273
  • 37
  • 540
  • 662