我有一个数据框如下
Customer OrderNo Tot_Orders
aaa 2 3
aaa 1 3
aaa 3 3
bbb 1 1
ccc 1 2
ccc 2 2
我希望按客户分组然后对Tot_Orders进行排序,之后我想在每个客户组中对OrderNo进行排序以获取
Customer OrderNo Tot_Orders
bbb 1 1
ccc 1 2
ccc 2 2
aaa 1 3
aaa 2 3
aaa 3 3
如何使用dplyr group_by并安排相同的操作?我试过了
df %>% group_by(Customer) %>% arrange(Tot_Orders)
但这没有帮助。提前谢谢!
答案 0 :(得分:0)
您可以尝试
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
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))