rdplyrtidyversepurrr

Split a list into separate data frame in R


So I have a list with me as below, what I want is to split them into three separate dataframes (with names as Banana/Strawberry & apple) as shown in expected output. I have already seen this (Splitting List into dataframe R) but its exact opposite of what I want. I dont want to combine then I want to split them into three dataframe with same name as list header.

list_a <- list(`Banana` = c(8.7), `Strawberry` = c(2.3), `Apple` = c(3.5))

DF1

Banana
8.7

DF2

Strawberry
2.3

DF3

Apple
3.5

Any Solution preferably in Tidyverse would be greatly appreciated. Actual problem has lot more columns in the list.


Solution

  • We can use imap to get the names and then use set_names

    library(purrr)
    library(dplyr)
    library(stringr)
    imap(list_a, ~ set_names(tibble(.x), .y)) %>%
            set_names(str_c("DF", 1:3)) %>% 
            list2env(.GlobalEnv)
    
    DF1
    # A tibble: 1 x 1
    #  Banana
    #   <dbl>
    #1    8.7
    DF2
    # A tibble: 1 x 1
    #  Strawberry
    #       <dbl>
    #1        2.3
    DF3
    # A tibble: 1 x 1
    #  Apple
    #  <dbl>
    #1   3.5
    

    If we need separate columns

    library(tibble)
    enframe(list_a) %>% 
         unnest(c(value)) %>% 
         group_split(rn = row_number(), keep = FALSE) %>%
         set_names(str_c("DF", 1:3)) %>% 
         list2env(.GlobalEnv)
    DF1
    # A tibble: 1 x 2
    #  name   value
    #  <chr>  <dbl>
    #1 Banana   8.7
    DF2
    # A tibble: 1 x 2
    #  name       value
    #  <chr>      <dbl>
    #1 Strawberry   2.3
    DF3
    # A tibble: 1 x 2
    #  name  value
    #  <chr> <dbl>
    #1 Apple   3.5