0

I have several dataframes with a single row per dataframe and I have an empty dataframe (let's name it 'total'). All dataframes have different count of columns, but some of them intersect. Total dataframe has all possible columns, so if I add any row from those dataframes it should match existed columns and fill values in accordance (if a column doesn't exist in adding row it should be filled as 0).

Example of dataframes with data:

A B C      B E      C E K J
1 2 5      4 2      3 2 5 7

Example of total dataframe:

A B C E K J
1 2 5 0 0 0
0 4 0 2 0 0
0 0 3 2 5 7

So, how to do that? I've tried various binds and inserts but they don't work - in some cases added row changes total dataframe column amount, in some cases added row just duplicates previous row etc.

anatol
  • 1,680
  • 2
  • 24
  • 47

1 Answers1

1

A possible solution:

library(tidyverse)

bind_rows(df1, df2, df3) %>% 
  mutate(across(everything(), ~ replace_na(.x, 0)))

#>   A B C E K J
#> 1 1 2 5 0 0 0
#> 2 0 4 0 2 0 0
#> 3 0 0 3 2 5 7
PaulS
  • 21,159
  • 2
  • 9
  • 26