使用dplyr按自定义顺序排列行

时间:2021-05-24 09:45:48

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.

使用dplyr中的Arrange函数,我们可以按升序或降序排列行。想知道如何按自定义顺序排列行。请参阅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

2 个解决方案

#1


15  

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")))

#2


1  

using data.table

df1[order(factor(Reg,levels = LETTERS[c(3,1,2)]))]

Here df1 is data.table

这里df1是data.table

#1


15  

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")))

#2


1  

using data.table

df1[order(factor(Reg,levels = LETTERS[c(3,1,2)]))]

Here df1 is data.table

这里df1是data.table