1

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.

Vin.Y
  • 13
  • 4

2 Answers2

0

Following solution doesn't have the same order of the columns or the Date doesn't appear multiple times. I really don't think there are a lot of reasons for either, so I am leaving the following solution.

It assumes Data is unique, if not don't use this approach.

merge(df1, df2, key = date)
# Date customer1 customer2 order1 order2
# 1    1         6         2      0      0
# 2    2         7         3      1      1
# 3    3         8         6      3      0
# 4    4         4         5      0      0
# 5    5         2         3      1      2
kangaroo_cliff
  • 6,067
  • 3
  • 29
  • 42
0

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

akrun
  • 874,273
  • 37
  • 540
  • 662