Cbind dataframes in an alternating order

Viewed 319

Let's say I have two data frames with the following columns.

df1 <- data.frame("A.One"=1:10, "A.Two"=1:10, "A.Three"=1:10)
df2 <- data.frame("B.One"=1:10, "B.Two"=1:10, "B.Three"=1:10)

I want to cbind them in a particular order (or cbind them normally and reorder them to achieve that order):

x <- magic_cbind(df1, df2)
colnames(x)

Desired output:

A.One B.One A.Two B.Two A.Three B.Three

That is, I wish to have them sorted by the suffix - first we have all Ones, then all Twos, according to the order they were in originally in each data frame. I hope this explanation makes sense...

This seems very simple but I can't figure it out and I don't really know what to search for, how to call this ordering...

2 Answers

We could use base R to do this. After cbinding the datasets, just order the columns based on the concantenated sequence of each dataset

cbind(df1, df2)[order(c(seq_along(df1), seq_along(df2)))]

Here's a tidyverse answer. Bind rows, use select to determine order of columns.

df1 <- data.frame("A.One"=1:10, "A.Two"=1:10, "A.Three"=1:10)
df2 <- data.frame("B.One"=1:10, "B.Two"=1:10, "B.Three"=1:10)

df3 <- cbind(df1, df2) %>%
  select(A.One, B.One, A.Two, B.Two, A.Three, B.Three)
Related