2017-09-11 1 views
-1

Ich möchte Städte in Reg so arrangieren, dass, wenn Reg und City übereinstimmen, dann sollte das oben in dieser Reg und verbleibende Städte sollten alphabetisch in aufsteigender Reihenfolge angeordnet sein. Ein Auszug von lang erforderlich ist unten angegeben.Einige spezielle Anordnung der Zeilen innerhalb von zwei Faktoren

erforderliche Ausgabe

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 ist unten:

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) 

Ich denke, die erforderliche Ausgabe arrange_if Funktion von dplyr erreicht werden könnte verwenden, aber konnte nicht herausfinden.

Antwort

2

So ähnlich?

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 
Verwandte Themen