简体   繁体   中英

dplyr arrange - sort groups by another column and then sort within each group

I have a data frame as below

 Customer  OrderNo  Tot_Orders
 aaa       2        3
 aaa       1        3
 aaa       3        3
 bbb       1        1
 ccc       1        2
 ccc       2        2

I want to group by customer and then sort on Tot_Orders after which I want to sort on OrderNo within each customer group to get

 Customer  OrderNo  Tot_Orders
 bbb       1        1
 ccc       1        2
 ccc       2        2
 aaa       1        3
 aaa       2        3
 aaa       3        3

How can I use dplyr group_by and arrange for the same? I tried

 df %>% group_by(Customer) %>% arrange(Tot_Orders)

but this didn't help. Thanks in advance!

You may try

library(dplyr)
df %>% 
  arrange(Tot_Orders, OrderNo) %>% 
  group_by(Customer)
#   Customer OrderNo Tot_Orders
#1      ccc       1          1
#2      bbb       1          2
#3      bbb       2          2
#4      aaa       1          3
#5      aaa       2          3
#6      aaa       3          3

df1 %>%
    arrange(Tot_Orders, OrderNo) %>% 
    group_by(Customer)
#    Customer OrderNo Tot_Orders
#1      bbb       1          1
#2      ccc       1          2
#3      ccc       2          2
#4      aaa       1          3
#5      aaa       2          3
#6      aaa       3          3

data

df <- structure(list(Customer = c("aaa", "aaa", "aaa", "bbb", "bbb", 
"ccc"), OrderNo = c(2L, 1L, 3L, 2L, 1L, 1L), Tot_Orders = c(3L, 
3L, 3L, 2L, 2L, 1L)), .Names = c("Customer", "OrderNo", "Tot_Orders"
), class = "data.frame", row.names = c(NA, -6L))

df1 <- structure(list(Customer = c("aaa", "aaa", "aaa", "bbb", "ccc", 
"ccc"), OrderNo = c(2L, 1L, 3L, 1L, 1L, 2L), Tot_Orders = c(3L, 
3L, 3L, 1L, 2L, 2L)), .Names = c("Customer", "OrderNo", "Tot_Orders"
), class = "data.frame", row.names = c(NA, -6L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM