Search code examples
rdataframecbind

Merge Two data frames column by column. (creating a table out of two data frames)


I have two data frames of this format

df1=data.frame( Date = c(1,2,3,4,5), customer1 = c(6,7,8,4,2), customer2 = 
c(2,3,6,5,3)... )
df2=data.frame( Date = c(1,2,3,4,5), order1 = c(0,1,3,0,1), order2 = 
c(0,1,0,0,2).. )

i want a result that intertwines the two data frames along with the date column.

Date Customer1 Order1 Date Customer2 Order2 Date ....
 1      6        0     1       2       0     1
 2      7        1     2       3       1     2
 3      8        3     3       6       0     3
 4      4        0     4       5       0     4
 5      2        1     5       3       2     5

I used a for loop running along the no. of columns and cbind to achieve the desired result. I wanted to know if there are simpler, more efficient ways to do it.


Solution

  • We can use order on the sequence of columns, then get the names of dataset based on the order, rbind with the 'Date' column to create a vector of column names. This can be used to order the columns in the full dataset (cbind(df1, df2))

    cbind(df1, df2)[c(rbind('Date', matrix(c(names(df1)[-1], 
           names(df2)[-1])[order(c(seq_along(df1)[-1], seq_along(df2)[-1]))], ncol=2)))]
    #      Date customer1 order1 Date.1 customer2 order2
    #1    1         6      0      1         2      0
    #2    2         7      1      2         3      1
    #3    3         8      3      3         6      0
    #4    4         4      0      4         5      0
    #5    5         2      1      5         3      2
    

    NOTE: It is better to have unique column names in the dataset