'create new database from two dataframes, with different rows
I have two dataframes, df1 of 19600 rows and df2 of 18830 rows, df2$id finds correspondence in the df1$id, while the remaining 770 have no correspondence, I would like to merge the two dataframes creating df3 with column df3$id equal to df1$id , if the row matches df2 it gives me values df2$value, otherwise it gives me 0, so in the 770 unmatched places I will have 0 as value
Solution 1:[1]
Using data.table():
library(data.table)
DT1 = data.table(ID = c(1:15),
Value = c(3:10))
DT2 = data.table(ID = c(1:10),
Value = c(7:13))
Join the tables and then recode the variable:
DT3 = DT2[DT1, on = .(ID)][, .(ID,Value)]
DT3[!ID %in% DT2$ID, Value := 0]
tail(DT3)
Output
ID Value
1: 10 9
2: 11 0
3: 12 0
4: 13 0
5: 14 0
6: 15 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jose |
