Search code examples
rrbind

rbind two different data frames that have different column names


I want to rbind two different data frames that have different column names

DF1 has 4 columns

Year Month Prec_CAN_45 Prec_CAN_85
2015 Jan 0.5 0.65
2100 Jan 0.6 0.75

DF2 has 3 columns

Year Month Prec_CAN_45
1998 Jan 0.3
2014 Jan 0.4

I want to create DF3 that has DF2 pasted above the DF1 rows in both columns (c3, c4)

Year Month Prec_CAN_45 Prec_CAN_85
1998 Jan 0.3 0.3
2014 Jan 0.4 0.4
2015 Jan 0.5 0.65
2100 Jan 0.6 0.75

Solution

  • The simplest way would be to simply duplicate the column Prec_CAN_45 in df2 and rename it to Prec_CAN_85. Then you can use rbind to combine the two data tables.

    Here's an easy dplyr solution:

    library(dplyr)
    
    df2 <- df2 %>% dplyr::mutate(Prec_CAN_85 = Prec_CAN_45)
    
    df3 <- rbind(df2, df1)
    
    df3
    #>    Year Month Prec_CAN_45 Prec_CAN_85
    #>   <dbl> <chr>       <dbl>       <dbl>
    #> 1  1998 Jan           0.3        0.3 
    #> 2  2014 Jan           0.4        0.4 
    #> 3  2015 Jan           0.5        0.65
    #> 4  2100 Jan           0.6        0.75
    

    Similarly, a base R solution might look like:

    df2$Prec_CAN_85 <- df2$Prec_CAN_45
    
    df3 <- rbind(df2, df1)
    
    df3
    #>    Year Month Prec_CAN_45 Prec_CAN_85
    #>   <dbl> <chr>       <dbl>       <dbl>
    #> 1  1998 Jan           0.3        0.3 
    #> 2  2014 Jan           0.4        0.4 
    #> 3  2015 Jan           0.5        0.65
    #> 4  2100 Jan           0.6        0.75