How to sum values of matching columns while merging two dataframes in r -
i have 2 dataframes in r
ship_no bay_1 bay_2 bay_3 bay_5 bay_6 abc 0 10 15 20 30 def 10 20 0 25 10 ert 0 10 0 10 0 ship_no bay_1 bay_2 bay_7 bay_5 bay_6 abc 10 10 10 0 0 def 10 10 0 15 10 ert 0 0 0 10 0
i want add columns values while merging above 2 dataframes on column key ship_no
my desired dataframe be
ship_no bay_1 bay_2 bay_3 bay_5 bay_6 bay_7 abc 10 20 15 20 30 10 def 20 30 0 40 20 0 ert 0 10 0 20 0 0
how can in r?
we can place datasets in list
, use rbindlist
rbind datasets, grouped 'ship_no', sum
of other columns
library(data.table) rbindlist(list(df1, df2), fill = true)[,lapply(.sd, sum, na.rm = true) , ship_no] # ship_no bay_1 bay_2 bay_3 bay_5 bay_6 bay_7 #1: abc 10 20 15 20 30 10 #2: def 20 30 0 40 20 0 #3: ert 0 10 0 20 0 0
another option dplyr
library(dplyr) bind_rows(df1, df2) %>% group_by(ship_no) %>% summarise_all(funs(sum(., na.rm = true))) # tibble: 3 x 7 # ship_no bay_1 bay_2 bay_3 bay_5 bay_6 bay_7 # <chr> <int> <int> <int> <int> <int> <int> #1 abc 10 20 15 20 30 10 #2 def 20 30 0 40 20 0 #3 ert 0 10 0 20 0 0
Comments
Post a Comment