Home > Net >  Combining two dataframes with alternating column position
Combining two dataframes with alternating column position

Time:06-07

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.

CodePudding user response:

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

CodePudding user response:

Alternatively, with purrr::pmap_dfc:

library(tidyverse)

pmap_dfc(list(df1, df2, names(df1), names(df2)),
   ~ data.frame(..1, ..2) %>% set_names(c(..3, ..4)))

#>   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

Or with:

bind_cols(df1, df2) %>% 
  relocate(map(1:ncol(df1), ~ c(.x, .x   ncol(df1))) %>% unlist())
  • Related