0

This is my data:

list_of_data <- list(mtcars[1:26,], mtcars[4:22,], mtcars[3:15,])

I want to merge the all dataframes by their rownames.

Merging a lot of data.frames

I know that Reduce comes pretty handy for a problem like this, but I am not able to get in inside my purrr workflow. Can anyone help me?

I am even not sure if reduce or reduce2 might be suited to get it work. This was my try but it does not work:

list_of_data %>%
    map(~select(.x, c(cyl, wt))) %>%
    reduce2(~merge(.x, .y,  all=TRUE))
Data Mastery
  • 1,555
  • 4
  • 18
  • 60

1 Answers1

2

If I understand correctly what's your intent:

library(tibble)
library(purrr)
library(dplyr)

list_of_data %>% 
  map(~select(.x, cyl, wt)) %>% 
  map(rownames_to_column) %>% 
  reduce(full_join, by = "rowname")

We can use dplyr::full_join with purrr::reduce to merge multiple dataframes. But to be able to merge by rownames, first we need to write them to a column. tibble::rownames_to_column does that. By default the column is called "rowname".

Iaroslav Domin
  • 2,698
  • 10
  • 19