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
We can use
factor
to change theorder
in a custom wayOr with
match
to get the index andarrange
on itIf we have multiple columns to
arrange
in descending orderusing data.table
Here df1 is data.table