rdataframerbind

How can I combine two dataframes with different lengths in R?


I have two dataframes, like those:

Year 1

and

enter image description here

I want to get something like that:

enter image description here

Here are the data frames for reproducibility:

df1 <- data.frame(descripcion_cuenta_N2 = c("Consumos", "Costes Personal", "Fungible Equipamiento", "Servicios"), anualidad = rep(2014, 4), valor = c(10, 11, 12, 13))
df2 <- data.frame(descripcion_cuenta_N2 = c("Consumos", "Costes Personal", "Fungible Equipamiento","Prestaciones", "Servicios"), anualidad = rep(2014, 5), valor = c(11, 20, 8, 9))

A dataframe in which missed positions are filled with 0, because in some cases I am not getting data frames with the same amount of rows, and in those cases rbind fails, and I get an error.

Which instruccion should use to combine those dataframes?

Thanks

PS: I know I can erase the repeated rows once the data frames are together.


Solution

  • Try using left_join in the dplyr package.

    library(dplyr)
    
    # make fake data
    df1 <- data.frame(id = c("A", "B", "C", "D", "E"), val = rpois(5, 5))
    df2 <- data.frame(id = c("A", "B", "C", "E"), val = rpois(4, 20))
    
    # use left_join
    df3 <- left_join(df1, df2, by = "id")
    
    # rename and set NAs to 0
    names(df3) <- c("id", "val", "val")
    df3[is.na(df3)] <- 0