Arranging rows in custom order using dplyr
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")))
Reorder rows using custom order
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.
Reorder rows of Pandas dataframe using custom order over multiple columns
You can represent Name
and Subject
as categorical variables:
names = ['Dan','Tim','Ari']
subjects = ['Science','History','Math']
df = df.astype({'Name': pd.CategoricalDtype(names, ordered=True),
'Subject': pd.CategoricalDtype(subjects, ordered=True)})
>>> df.sort_values(['Name', 'Subject'])
Name Subject Test1 Test2
7 Dan Science 58 28
8 Dan History 10 50
6 Dan Math 10 1
1 Tim Science 46 78
2 Tim History 54 61
0 Tim Math 10 5
4 Ari Science 83 32
5 Ari History 39 43
3 Ari Math 10 7
>>> df.sort_values(['Subject', 'Name'])
Name Subject Test1 Test2
7 Dan Science 58 28
1 Tim Science 46 78
4 Ari Science 83 32
8 Dan History 10 50
2 Tim History 54 61
5 Ari History 39 43
6 Dan Math 10 1
0 Tim Math 10 5
3 Ari Math 10 7
Arrange rows in custom order using R
You can make country
an ordered factor.
library(dplyr)
country <- rep(c("AT","BE","CY","DE","EE"),10)
value <- seq(1, 50)
# chenged this to a vector rather than a data frame
target_cc <- c("DE","CY","BE","AT","EE")
df %>%
mutate(country = factor(country, levels = target_cc)) %>%
arrange(country)
Reordering rows in data frame (R)
You need to change the Group.1
column to factor. After that, you can use order
to re-order the rows based on Group.1
as follows.
df2$Group.1 <- factor(df2$Group.1, levels = c('B', 'D', 'A', 'C', 'E', 'F'))
df3 <- df2[order(df2$Group.1), ]
df3
# Group.1 x
# 2 B 15.333333
# 4 D 4.916667
# 1 A 14.500000
# 3 C 2.083333
# 5 E 3.500000
# 6 F 16.666667
DATA
df2 <- read.table(text = "Group.1 x
A 14.500000
B 15.333333
C 2.083333
D 4.916667
E 3.500000
F 16.666667",
header = TRUE, stringsAsFactors = FALSE)
Reordering rows in a tables following a custom order
Instead of replacing the values with the labels, convert the vector into ordered
:
q1 <- sample(c(1:5, 77, 99), 100, T)
q1 <- ordered(q1, labels= c("Very good", "Good", "Average",
"Poor", "Very poor", "Unsure", "No answer"))
table(q1)
q1
Very good Good Average Poor Very poor Unsure No answer
15 14 13 21 9 16 12
Reorder matrix rows by custom sort
This is sorting a matrix you can easily find this on google searching for
r sorting matrix
Have a look here
Related Topics
Multiple Boxplots Using Ggplot
Developing Geographic Thematic Maps with R
Disregarding Simple Warnings/Errors in Trycatch()
Skip Specific Rows Using Read.CSV in R
How to Remove Empty Data Frames from a List
Applying R Script Prepared for Single File to Multiple Files in the Directory
Importing Only Every Nth Row from a .CSV File in R
Installation of Rodbc on Os X Yosemite
How to Merge Two Columns in R with a Specific Symbol
How to Skip an Error in a Loop
Average Values of a Point Dataset to a Grid Dataset
Enter New Column Names as String in Dplyr's Rename Function