我希望以这样的方式安排Reg内的城市,如果Reg和City匹配那么Reg应该位于Reg的顶部,剩余的城市应按字母顺序按升序排列。下面给出了长期需要的提取物。
所需输出
Reg City Res Pop Pop1
A A Total 204 19
A A Rural 101 10
A A Urban 103 9
A a Total 109 11
A a Rural 55 5
A a Urban 54 6
A b Total 95 8
A b Rural 46 5
A b Urban 49 3
B B Total 325 24
B B Rural 166 10
B B Urban 159 14
B c Total 119 7
B c Rural 53 0
B c Urban 66 7
B d Total 108 9
B d Rural 61 6
B d Urban 47 3
B e Total 98 8
B e Rural 52 4
B e Urban 46 4
MWE MWE如下:
df6 <-
structure(list(Reg = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A",
"B"), class = "factor"), City = c("a", "a", "a", "A", "A", "A",
"b", "b", "b", "B", "B", "B", "c", "c", "c", "d", "d", "d", "e",
"e", "e"), Res = c("Total", "Rural", "Urban", "Total", "Rural",
"Urban", "Total", "Rural", "Urban", "Total", "Rural", "Urban",
"Total", "Rural", "Urban", "Total", "Rural", "Urban", "Total",
"Rural", "Urban"), Pop = c(109L, 55L, 54L, 204L, 101L, 103L,
95L, 46L, 49L, 325L, 166L, 159L, 119L, 53L, 66L, 108L, 61L, 47L,
98L, 52L, 46L), Pop1 = c(11L, 5L, 6L, 19L, 10L, 9L, 8L, 5L, 3L,
24L, 10L, 14L, 7L, 0L, 7L, 9L, 6L, 3L, 8L, 4L, 4L)), class = "data.frame", row.names = c(NA,
-21L), .Names = c("Reg", "City", "Res", "Pop", "Pop1"))
library(dplyr)
df6 %>%
arrange(Reg, City)
我想可以使用arrange_if
中的dplyr
函数获得所需的输出,但无法弄清楚。
答案 0 :(得分:2)
这样的东西?
library(dplyr)
df6 %>%
mutate(match.RegCity = Reg==City) %>%
arrange(Reg, #arrange by Reg first
desc(match.RegCity), # then by whether Reg==City (TRUE before FALSE)
City) %>% # then by City
select(-match.RegCity)
Reg City Res Pop Pop1
1 A A Total 204 19
2 A A Rural 101 10
3 A A Urban 103 9
4 A a Total 109 11
5 A a Rural 55 5
6 A a Urban 54 6
7 A b Total 95 8
8 A b Rural 46 5
9 A b Urban 49 3
10 B B Total 325 24
11 B B Rural 166 10
12 B B Urban 159 14
13 B c Total 119 7
14 B c Rural 53 0
15 B c Urban 66 7
16 B d Total 108 9
17 B d Rural 61 6
18 B d Urban 47 3
19 B e Total 98 8
20 B e Rural 52 4
21 B e Urban 46 4