Home > Software engineering >  Merging tables in the same order
Merging tables in the same order

Time:05-18

I have 3 tables that I want to merge:

B1_1   2   3 4 5
   1 0.5 0.5 0 0
   3 0.0 0.0 1 0
   5 0.0 0.0 1 0
   6 0.0 0.0 0 1

B1_1    2    3    4
   1 0.25 0.25 0.50
   3 0.50 0.50 0.00
   5 0.00 0.00 1.00
   6 0.00 0.00 1.00

B1_1   2   4   5
   5 0.5 0.0 0.5
   6 0.0 1.0 0.0
   7 0.0 1.0 0.0

When I use cbind() I get an error saying that the number of rows of matrices must match. Is there a way to merge them, even tho numbers of rows do not match and at the same time keeping the B1_1 column in the same order, since it's (1,3,5,6), (1,3,5,6) and (5,6,7)?

Thank you!

CodePudding user response:

Maybe you want something like this:

library(dplyr)
list(df1,df2,df3) %>% reduce(bind_rows)

Output:

   B1_1   X2   X3  X4  X5
1     1 0.50 0.50 0.0 0.0
2     3 0.00 0.00 1.0 0.0
3     5 0.00 0.00 1.0 0.0
4     6 0.00 0.00 0.0 1.0
5     1 0.25 0.25 0.5  NA
6     3 0.00 0.50 0.0  NA
7     5 0.00 0.00 1.0  NA
8     6 0.00 0.00 1.0  NA
9     5 0.50   NA 0.0 0.5
10    6 0.00   NA 1.0 0.0
11    7 0.00   NA 1.0 0.0

Data

df1 <- data.frame(B1_1 = c(1,3,5,6),
                  "2" = c(0.5,0, 0, 0),
                  "3" = c(0.5,0,0,0),
                  "4" = c(0,1,1,0),
                  "5" = c(0,0,0,1))

df2 <- data.frame(B1_1 = c(1,3,5,6),
                  "2" = c(0.25,0, 0, 0),
                  "3" = c(0.25,0.5,0,0),
                  "4" = c(0.5,0,1,1))

df3 <- data.frame(B1_1 = c(5,6,7),
                  "2" = c(0.5,0, 0),
                  "4" = c(0,1,1),
                  "5" = c(0.5,0,0))

CodePudding user response:

You can join tables having the shared columns together:

df1 <- data.frame(B1_1 = c(1,3,5,6), y = 1)
df2 <- data.frame(B1_1 = c(5,6,7), y = 1)
dplyr::full_join(df1, df2)
#> Joining, by = c("B1_1", "y")
#>   B1_1 y
#> 1    1 1
#> 2    3 1
#> 3    5 1
#> 4    6 1
#> 5    7 1

Created on 2022-05-17 by the reprex package (v2.0.0)

  • Related