0

I have 14 datasets that I want to merge in R. All of them have 20 columns in common, but then most have some extra columns. I want to merge them together by the columns they have in common, leaving as "NA" the empty data but still keeping the columns that are not common to all. I am new to R but have tried everything I found online to no avail. Any help would be really appreciated.

Thank you!

  • Can you please show some sample data (e.g. 3 rows each) and what you want it to look like after the merge? Are the rows all separate cases? – Elin Nov 19 '20 at 16:18

1 Answers1

0

You should be able to use dplyr::bind_rows. Here's a quick example showing the non-shared field will be included:

df1 <- data.frame(
  x = c(1:10),
  y = c(rep('N', 5), rep('y', 5))
)

df2 <- data.frame(
  x = c(11:20),
  y = c(rep('N', 5), rep('y', 5)),
  z = c(1:10)
)

df3 <- bind_rows(df1, df2)

df3 output:

    x y  z
1   1 N NA
2   2 N NA
3   3 N NA
4   4 N NA
5   5 N NA
6   6 y NA
7   7 y NA
8   8 y NA
9   9 y NA
10 10 y NA
11 11 N  1
12 12 N  2
13 13 N  3
14 14 N  4
15 15 N  5
16 16 y  6
17 17 y  7
18 18 y  8
19 19 y  9
20 20 y 10
TTS
  • 1,818
  • 7
  • 16
  • 2
    Note for OP - *hopefully* your [data frames are in a list](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207), in which case you can use `bind_rows(my_list_of_data_frames)`. – Gregor Thomas Nov 19 '20 at 16:18
  • Thank you very much! This is super helpful. However I get the following error: Can't combine `..1$FECHA` and `..3$FECHA` . – joanmarti Nov 19 '20 at 17:00
  • It's telling you the columns you are trying to combine are not of the same datatype (character vs. double). One way around this is to `mutate_all` with `as.character` to set all columns to a character datatype. – TTS Nov 19 '20 at 17:13