如何在 R 中组合两个不同长度的数据帧?

The*_*oot 2 r dataframe rbind

我有两个数据框,如下所示:

第一年

在此处输入图片说明

我想得到这样的东西:

在此处输入图片说明

以下是可重复性的数据框:

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))
Run Code Online (Sandbox Code Playgroud)

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.

小智 6

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
Run Code Online (Sandbox Code Playgroud)