Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading