Arranging rows in custom order using dplyr

后端 未结 2 612
礼貌的吻别
礼貌的吻别 2020-12-07 18:00

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.

相关标签:
2条回答
  • 2020-12-07 18:29

    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")))
    
    0 讨论(0)
  • 2020-12-07 18:31

    using data.table

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

    Here df1 is data.table

    0 讨论(0)
提交回复
热议问题