Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Output separate dataframes in a list using purrr::map_dfr()

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try using purrr::transpose:

map(transpose(test_dat), bind_rows)

From the purrr cheatsheet here is a little visual aid to understand what that function does:

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  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading