0

Let's say I have these 3 dataframes (In my case I have tens of such data frames).

library(dplyr)

dm1 = data.frame(x = 1:10, y = 20:29)

dm2 = data.frame(x = 1:5, z = 100:104)

dm3 = data.frame(x = 2:8, m = 200:206)

and I wish to merge them using the function left_join so that the merge can take into account the column x. When I am trying to use this function, I am able to merge only two dataframes together but not the 3 all at once. The desired output is as follows

    x  y   z   m
1   1 20 100  NA
2   2 21 101 200
3   3 22 102 201
4   4 23 103 202
5   5 24 104 203
6   6 25  NA 204
7   7 26  NA 205
8   8 27  NA 206
9   9 28  NA  NA
10 10 29  NA  NA

Anas116
  • 797
  • 2
  • 9
  • 1
    Use `purrr::reduce(list(dm1, dm2, dm3), dplyr::left_join)` – Maël Jul 24 '23 at 08:37
  • Thank you so much. Can you share the answer in the anwer section so everyone can see it ? – Anas116 Jul 24 '23 at 08:38
  • 1
    Try save all the data frames into a list, then call `purrr::reduce(.x = list_dfs, .f ~ = left_join(.x, .y, by = "x", suffix = c("", "_suffix")))` – Su Na Jul 24 '23 at 08:39
  • 2
    This question has many duplicates. It's better not to spread the answers so people should be directed towards the link on top of your answer. – Maël Jul 24 '23 at 08:39
  • 1
    library(dplyr) df <- dm1 |> left_join(dm2, by = "x") |> left_join(dm3, by = "x") – Rodrigo Jul 24 '23 at 11:09

0 Answers0