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
  • 859
  • 5
  • 11

3 Answers3

3

You could also use split:

split(df[-1], df[1])
onyambu
  • 49,350
  • 3
  • 19
  • 45
1

A second option would be using dplyr for grouped variables:

library(dplyr)

df %>% 
  group_split(a, .keep = FALSE)
zx8754
  • 46,390
  • 10
  • 104
  • 180
DPH
  • 3,362
  • 1
  • 6
  • 16
1

We can use:

library(tibble)
as.list(deframe(df))
Elletlar
  • 2,991
  • 7
  • 29
  • 34
akrun
  • 789,025
  • 32
  • 460
  • 575