【问题标题】:how to bind rows of two data frames such that the rows with same value in ID column stays next to each other如何绑定两个数据帧的行,使 ID 列中具有相同值的行彼此相邻
【发布时间】:2019-04-04 11:15:51
【问题描述】:

我有两个看起来像这样的数据框:

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

我想将它们绑定在一起(按行),这样生成的数据框将如下所示:

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

意思是,两个数据帧中具有相同cust_id 的行在绑定的数据帧中彼此相邻。

提前感谢您的宝贵时间。

【问题讨论】:

  • 查看here 以了解合并数据帧的不同选项
  • 使用 dplyr,bind_rows(data.one, data.two) %>% arrange( cust_id, -stats)

标签: r dataframe


【解决方案1】:

也许 dplyr 中的排列功能会很有用:

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)

【讨论】:

    【解决方案2】:

    只需使用 rbind 将 Thema 绑定在一起,然后使用 order 对数据框进行排序:

    mydata <- rbind(data1, data2)
    
    mydata[order(mydata$cust_id), ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      相关资源
      最近更新 更多