0

I have two data frames that looks like:

data.one:

          cust_id stats  AIRLINE AUTO RENTAL CLOTHING STORES
   1:         495   SUM 45493.42     3103.90        20927.56
   2:         692   SUM 39954.78        0.00        20479.60
   3:         728   SUM 25813.03     3504.74         5924.71
   4:        1794   SUM     0.00        0.00            0.00
   5:        3060   SUM     0.00        0.00         7146.31

data.two:

         cust_id stats AIRLINE AUTO RENTAL CLOTHING STORES
   1:         495   MAX 4950.00     1000.00            3140
   2:         692   MAX 6479.71        0.00            1880
   3:         728   MAX 5642.68     1752.37            1395
   4:        1794   MAX    0.00        0.00               0
   5:        3060   MAX    0.00        0.00            1338

I want to bind them together (row-wise) such that the resulting data frame will look like this:

           cust_id stats AIRLINE AUTO RENTAL CLOTHING STORES
   1:         495   SUM   45493.42     3103.90        20927.56
   2:         495   MAX   4950.00      1000.00        3140
   3:         692   SUM   39954.78     0.00           20479.60
   4:         692   MAX   6479.71      0.00           1880
   5:         728   SUM   25813.03     3504.74        5924.71
   6:         728   MAX   5642.68      1752.37        1395
   .
   .
   .

meaning, rows with same cust_id from both the data frames stay next to each other in the binded data frame.

Thank you for your time in advance.

Cettt
  • 11,460
  • 7
  • 35
  • 58
techKid-Rinshad
  • 177
  • 1
  • 2
  • 9
  • 1
    Have a look [here](https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right) for different options to merge data frames – CIAndrews Apr 04 '19 at 11:20
  • With dplyr, `bind_rows(data.one, data.two) %>% arrange( cust_id, -stats)` – amatsuo_net Apr 04 '19 at 11:20

2 Answers2

1

Maybe the arrange function in dplyr would be useful:

custid <- c(111,222,333)
otherVar <- c(1,2,3)

df1 <- data.frame(custid, otherVar)

custid <- c(222,333,444)
otherVar <- c(2,3,4)

df2 <- data.frame(custid, otherVar)

df <- df1 %>%
  bind_rows(df2) %>%
  arrange(custid)
olorcain
  • 1,230
  • 1
  • 9
  • 12
0

Just bind Thema together using rbind and then sort the dataframe using order:

mydata <- rbind(data1, data2)

mydata[order(mydata$cust_id), ]
Cettt
  • 11,460
  • 7
  • 35
  • 58