Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder rows using custom order

Tags:

r

dplyr

Given data:

library(data.table) DT = data.table(category=LETTERS[1:3], b=1:3) DT #    category b # 1:        A 1 # 2:        B 2 # 3:        C 3 

Using dplyr, how to rearrange rows to get specific order c("C", "A", "B") in category?

#    category b # 1:        C 3 # 2:        A 1 # 3:        B 2 
like image 285
Daniel Krizian Avatar asked Oct 24 '14 13:10

Daniel Krizian


People also ask

How do I sort rows in a specific order in R?

Data Manipulation in R Sort a data frame rows in ascending order (from low to high) using the R function arrange() [dplyr package] Sort rows in descending order (from high to low) using arrange() in combination with the function desc() [dplyr package]

How do I arrange rows in ascending order in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

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

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


1 Answers

First, create a vector with the letters in the desired order. Then match* the vector with the variable to be sorted. match returns indices of (first) matches, which can be plugged into slice:

library(dplyr)  # create a vector with letters in the desired order x <- c("C", "A", "B")  DT %>%   slice(match(x, category)) #   category b # 1        C 3 # 2        A 1 # 3        B 2 

Another way would be to convert "category" to a factor, set levels to the desired order, and use arrange:

DT %>%   mutate(category =  factor(category, levels = x)) %>%   arrange(category)     #   category b # 1        C 3 # 2        A 1 # 3        B 2 

*The match method is inspired by this answer.

like image 124
Henrik Avatar answered Sep 29 '22 18:09

Henrik