我希望根据数据帧的单独列值,按其单独的组对数据帧进行排序。示例数据帧如下:
集团
|
答案
|
频率
|
A.
|
苹果
|
12
|
B
|
苹果
|
8.
|
A.
|
橙色
|
11
|
B
|
橙色
|
3.
|
A.
|
香蕉
|
20
|
B
|
香蕉
|
5.
|
A.
|
菠萝蜜
|
10
|
B
|
菠萝蜜
|
9
|
A.
|
菠萝
|
5.
|
B
|
菠萝
|
3.
|
A.
|
梨
|
20
|
B
|
梨
|
20
|
df_sample = structure(list(Group = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L), .Label = c("A", "B"), class = "factor"),
Answer = structure(c(1L, 1L, 4L, 4L, 2L, 2L, 3L, 3L, 6L,
6L, 5L, 5L), .Label = c("Apple", "Banana", "Jackfruit", "Orange",
"Pear", "Pineapple"), class = "factor"), Frequency = c(12L,
8L, 11L, 3L, 20L, 5L, 10L, 9L, 5L, 3L, 20L, 20L)), class = "data.frame", row.names = c(NA,
-12L))
我希望根据组列对它们进行排序,并根据每组的频率输出前3个答案。结果应如下表所示。
集团
|
答案(前三名)
|
频率
|
A.
|
梨
|
20
|
A.
|
香蕉
|
20
|
A.
|
苹果
|
12
|
B
|
梨
|
20
|
B
|
菠萝蜜
|
9
|
B
|
苹果
|
8.
|
如果我没有错,代码应该是单行代码,但我不确定如何完成它
df_sample %>% group_by(Group) %>% order(Frequency, decreasing = T)
谢谢!