Reorder rows using custom order

后端 未结 1 394
轻奢々
轻奢々 2020-12-04 11:05

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
相关标签:
1条回答
  • 2020-12-04 11:17

    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.

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