1

I want to bind these two (df1,df2) datasets:

df1f <- mtcars %>% filter(am == 1)
df1 <- cbind(n = table(df1f$carb),
      prop.table(with(df1f, table(carb, cyl)), margin = 1))
> df1  
  n 4         6         8
1 4 1 0.0000000 0.0000000
2 4 1 0.0000000 0.0000000
4 3 0 0.6666667 0.3333333
6 1 0 1.0000000 0.0000000
8 1 0 0.0000000 1.0000000
df2f <- mtcars %>% filter(cyl == 4)
df2 <- prop.table(with(df2f, table(carb, gear)), margin = 1)
> df2
    gear
carb         3         4         5
   1 0.2000000 0.8000000 0.0000000
   2 0.0000000 0.6666667 0.3333333

I tried some functions like cbind(), merge() or list(df1,df2) %>% reduce(bind_rows) but they all resulted in an error message (usually due to the different number of rows)

Is there a way to bind these tables in a way that would result in a side-by-side output like this?

  n 4         6         8     carb         3         4         5  
1 4 1 0.0000000 0.0000000        1 0.2000000 0.8000000 0.0000000
2 4 1 0.0000000 0.0000000        2 0.0000000 0.6666667 0.3333333
4 3 0 0.6666667 0.3333333
6 1 0 1.0000000 0.0000000
8 1 0 0.0000000 1.0000000

Thank you!

Sascha
  • 159
  • 6

1 Answers1

1

Update

If you have multiple dataframes, you can try Reduce

Reduce(
    function(x, y) {
        cbind(
            x,
            rbind(
                y,
                matrix(nrow = nrow(x) - nrow(y), ncol = ncol(y))
            )
        )
    },
    list(df1,df2,df3,df4,df5,df6)
)

Do you mean something like this?

cbind(
    df1,
    rbind(
        df2,
        matrix(nrow = nrow(df1) - nrow(df2), ncol = ncol(df2))
    )
)

which gives

  n 4         6         8   3         4         5
1 4 1 0.0000000 0.0000000 0.2 0.8000000 0.0000000
2 4 1 0.0000000 0.0000000 0.0 0.6666667 0.3333333
4 3 0 0.6666667 0.3333333  NA        NA        NA
6 1 0 1.0000000 0.0000000  NA        NA        NA
8 1 0 0.0000000 1.0000000  NA        NA        NA
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81