1

I'm relatively new to R so please accept my apologies if this seems obvious/silly question- I have tried googling to no avail.

I have two dataframes that I would like to append without merging or losing any data. I hope the below explains what I mean.

I've tried rbind, cbind, merge, but none seem to work in the way I need. I wondered if anyone had any tips?

Example

Maël
  • 45,206
  • 3
  • 29
  • 67
visibleAce
  • 47
  • 1
  • 5
  • Use `dplyr::bind_rows`, or `data.table::rbindlist` – Maël May 16 '22 at 14:31
  • Welcome to SO. Please read the tag information about asking questions: " Please use minimal reproducible example(s) others can run using copy & paste. Use dput() for data & specify all non-base packages with library(). Don't embed pictures for data or code, use indented code blocks instead. " Please do not post images of data. – Peter May 16 '22 at 14:31
  • Does this answer your question? [Combine two data frames by rows (rbind) when they have different sets of columns](https://stackoverflow.com/questions/3402371/combine-two-data-frames-by-rows-rbind-when-they-have-different-sets-of-columns) – Maël May 16 '22 at 14:32

2 Answers2

3

As mentioned in the comments, you can use dplyr::bind_rows or data.table::rbindlist:

dplyr::bind_rows(df1, df2)
data.table::rbindlist(list(df1, df2), fill = T)
Maël
  • 45,206
  • 3
  • 29
  • 67
2

An option is using the rbind.fill from plyr function like this:

df1 <- data.frame(Name = c("A", "B", "C"),
                  Value1 = c(1,2,3),
                  Value4 = c(7,3,5))

df2 <- data.frame(Name = c("A", "B", "C", "D"),
                  Value1 = c(1,2,3,4),
                  Value2 = c(5,6,1,7))

library(plyr)
rbind.fill(df2,df1)

Output:

 Name Value1 Value2 Value4
1    A      1      5     NA
2    B      2      6     NA
3    C      3      1     NA
4    D      4      7     NA
5    A      1     NA      7
6    B      2     NA      3
7    C      3     NA      5

bind_rows from dplyr option like @Maël mentioned in comments:

library(dplyr)
bind_rows(df2,df1)

Output:

  Name Value1 Value2 Value4
1    A      1      5     NA
2    B      2      6     NA
3    C      3      1     NA
4    D      4      7     NA
5    A      1     NA      7
6    B      2     NA      3
7    C      3     NA      5
Quinten
  • 35,235
  • 5
  • 20
  • 53