r - Some special arrangement of rows within two factors -


i want arrange cities within reg in such way if reg , city match should come @ top in reg , remaining cities should arranged alphabetically in ascending order. extract long required given below.

required output

  reg city   res pop pop1       total 204   19       rural 101   10       urban 103    9       total 109   11       rural  55    5       urban  54    6       b total  95    8       b rural  46    5       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 below:

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) 

i guess required output might attained using arrange_if function dplyr not figure out. highly appreciated. thanks

something this?

library(dplyr)  df6 %>%   mutate(match.regcity = reg==city) %>%   arrange(reg,                 #arrange reg first           desc(match.regcity), # whether reg==city (true before false)           city) %>%            # city   select(-match.regcity)     reg city   res pop pop1 1       total 204   19 2       rural 101   10 3       urban 103    9 4       total 109   11 5       rural  55    5 6       urban  54    6 7       b total  95    8 8       b rural  46    5 9       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 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -