Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arranging rows in custom order using dplyr

With arrange function in dplyr, we can arrange row in ascending or descending order. Wonder how to arrange rows in custom order. Please see MWE.

Reg <- rep(LETTERS[1:3], each = 2) Res <- rep(c("Urban", "Rural"), times = 3) set.seed(12345) Pop <- rpois(n = 6, lambda = 500000) df <- data.frame(Reg, Res, Pop)  df    Reg   Res    Pop 1    A Urban 500414 2    A Rural 500501 3    B Urban 499922 4    B Rural 500016 5    C Urban 501638 6    C Rural 499274  df %>%   arrange() 

Desired Output

   Reg   Res    Pop 5    C Urban 501638 6    C Rural 499274 1    A Urban 500414 2    A Rural 500501 3    B Urban 499922 4    B Rural 500016 
like image 979
MYaseen208 Avatar asked Sep 09 '17 09:09

MYaseen208


People also ask

How do I reorder rows in dplyr?

Arrange rowsThe dplyr function arrange() can be used to reorder (or sort) rows by one or more variables. Instead of using the function desc(), you can prepend the sorting variable by a minus sign to indicate descending order, as follow. If the data contain missing values, they will always come at the end.

How do I change the order of rows in R?

To change the row order in an R data frame, we can use single square brackets and provide the row order at first place.

What is the use of Arrange () with dplyr package?

arrange() orders the rows of a data frame by the values of selected columns.

What does arrange () do in R?

What is the arrange() function in R? The arrange() function in R programming is used to reorder the rows of a data frame/table by using column names. These columns are passed as the expression in the function.


2 Answers

We can use factor to change the order in a custom way

df %>%     arrange(factor(Reg, levels = LETTERS[c(3, 1, 2)]), desc(Res), desc(Pop)) #  Reg   Res    Pop #1   C Urban 501638 #2   C Rural 499274 #3   A Urban 500414 #4   A Rural 500501 #5   B Urban 499922 #6   B Rural 500016 

Or with match to get the index and arrange on it

df %>%     arrange(match(Reg, c("C", "A", "B")), desc(Res), desc(Pop)) 

If we have multiple columns to arrange in descending order

df %>%      arrange_at(2:3, desc) %>%      arrange(match(Reg, c("C", "A", "B"))) 
like image 147
akrun Avatar answered Sep 28 '22 00:09

akrun


I used the slice() function:

   df %<>%    slice(5,6,1:4) 
like image 43
Peter Dorey Avatar answered Sep 28 '22 01:09

Peter Dorey