Home > front end >  Output separate dataframes in a list using purrr::map_dfr()
Output separate dataframes in a list using purrr::map_dfr()

Time:07-06

I'm looking to sequentially read in data and the transform it in two disparate scripts then combine the results into a list of dataframes:

library(tidyverse)

dat_list <- list(as_tibble(mtcars),as_tibble(mtcars),as_tibble(mtcars))


test_func <- function(x) {
  dat <- x
  
  gear_avg <- dat %>% 
    group_by(gear) %>% 
    summarize(value=mean(mpg))
  
  carb_avg <- dat %>% 
    group_by(carb) %>% 
    summarize(value=mean(mpg))
  
  df_list <- list(as_tibble(gear_avg),as_tibble(carb_avg))
  return(df_list)
}

test_dat <- map_dfr(dat_list, test_func)

desired_output <-
  list(
    gear_avg = test_dat %>% filter(!is.na(gear)) %>% select(-carb),
    carb_avg = test_dat %>% filter(!is.na(carb)) %>% select(-gear)
  )

This is what I would expect to work but it just outputs a single dataframe.

CodePudding user response:

Try using purrr::transpose:

map(transpose(test_dat), bind_rows)

From the enter image description here

Also, test_func does not return anything. So, in your reprex you should add the following as the last line: return(df_list)


Output

[[1]]
# A tibble: 9 x 2
   gear value
  <dbl> <dbl>
1     3  16.1
2     4  24.5
3     5  21.4
4     3  16.1
5     4  24.5
6     5  21.4
7     3  16.1
8     4  24.5
9     5  21.4

[[2]]
# A tibble: 18 x 2
    carb value
   <dbl> <dbl>
 1     1  25.3
 2     2  22.4
 3     3  16.3
 4     4  15.8
 5     6  19.7
 6     8  15  
 7     1  25.3
 8     2  22.4
 9     3  16.3
10     4  15.8
11     6  19.7
12     8  15  
13     1  25.3
14     2  22.4
15     3  16.3
16     4  15.8
17     6  19.7
18     8  15  
  • Related