Home > OS >  How to append dataframes without losing/merging any data in R?
How to append dataframes without losing/merging any data in R?

Time:05-17

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

CodePudding user response:

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)

CodePudding user response:

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
  •  Tags:  
  • r
  • Related