I have two dataframes, I need to add two columns from those two and store the result in the original bigger dataframe, but the bigger dataframe has lot more 'branch' column than the smaller one. I tried using match but the non matching branches the sum is NA
Sample code:
> df1 <- data.frame(branch = letters[seq(1,5)],
+ rev = seq(10,50,10),
+ stringsAsFactors = 0)
> df1
branch rev
1 a 10
2 b 20
3 c 30
4 d 40
5 e 50
>
> df2 <- data.frame(branch = c('b','d'),
+ Amt = c(10,10),
+ stringsAsFactors = 0)
> df2
branch Amt
1 b 10
2 d 10
>
> df1$rev + df2[match(df1$branch,df2$branch),2,drop = 1]
[1] NA 30 NA 50 NA
>
Expected Output
> df1
branch rev
1 a 10
2 b 30
3 c 30
4 d 50
5 e 50
>
I tried using left join as below:
> left_join(df1, df2, by = 'branch')
branch rev Amt
1 a 10 NA
2 b 20 10
3 c 30 NA
4 d 40 10
5 e 50 NA
> df1 <- left_join(df1, df2, by = 'branch')
> df1[is.na(df1)] <- 0
> df1
branch rev Amt
1 a 10 0
2 b 20 10
3 c 30 0
4 d 40 10
5 e 50 0
> df1$rev <- df1$rev + df1$Amt
> df1
branch rev Amt
1 a 10 0
2 b 30 10
3 c 30 0
4 d 50 10
5 e 50 0
> df1$Amt <- NULL
> df1
branch rev
1 a 10
2 b 30
3 c 30
4 d 50
5 e 50
>
Could someone let me know if there's a simpler solution for this.