Search code examples
rdataframecbind

Combining two dataframes with alternating column position


I have these two dataframes:

df1 <- tibble(b = 1:4,
       a = 1:4,
       c = 1:4)

df2 <- tibble(b_B = 1:4,
              a_A = 1:4,
              c_C = 1:4)

> df1
# A tibble: 4 x 3
      b     a     c
  <int> <int> <int>
1     1     1     1
2     2     2     2
3     3     3     3
4     4     4     4
> df2
# A tibble: 4 x 3
    b_B   a_A   c_C
  <int> <int> <int>
1     1     1     1
2     2     2     2
3     3     3     3
4     4     4     4

I would like to combine this two dataframes keeping the column position of df1 and entering the columns of df2 alternating with df1

Desired output:

  b b_B a a_A c c_C
1 1   1 1   1 1   1
2 2   2 2   2 2   2
3 3   3 3   3 3   3
4 4   4 4   4 4   4

I have tried:

cbind(df1, df2) %>% 
  select(gtools::mixedsort(colnames(.)))

  a a_A b b_B c c_C
1 1   1 1   1 1   1
2 2   2 2   2 2   2
3 3   3 3   3 3   3
4 4   4 4   4 4   4

But this orders the columns alphabetically.


Solution

  • We can use the matrix route to bind the column names into a dim structure and then concatenate (c)

    library(dplyr)
    bind_cols(df1, df2) %>% 
       dplyr::select(all_of(c(matrix(names(.), ncol = 3, byrow = TRUE))))
    

    -output

    # A tibble: 4 × 6
          b   b_B     a   a_A     c   c_C
      <int> <int> <int> <int> <int> <int>
    1     1     1     1     1     1     1
    2     2     2     2     2     2     2
    3     3     3     3     3     3     3
    4     4     4     4     4     4     4