Custom sorting (non-alphabetical)

后端 未结 4 1518
误落风尘
误落风尘 2020-11-30 06:22

I have a categorical data set that looks similar to:

A < -data.frame(animal = c(\"cat\",\"cat\",\"cat\",\"dog\",\"dog\",\"dog\",\"elephant\",\"elephant\",         


        
相关标签:
4条回答
  • 2020-11-30 07:07

    In a vein similar to how agstudy did it, I'd present the 'tidyverse' way of presenting the ordering:

    A$animal <- factor(A$animal, levels = c("dog", "elephant","cat"))
    A$color <- factor(A$color, levels = c("green", "blue", "red"))
    

    Then we load dplyr or the whole tidyverse and can do

    arrange(A, animal, color)
    

    or simply

    A %>% arrange(animal, color)
    

    where %>% is the 'pipe' operator in r, and can be accessed by using Ctrl + Shift + m

    0 讨论(0)
  • 2020-11-30 07:15

    One other thing worth noting - you don't have to convert the class to do this. You can simply order by the factor of the variable. Thus preserving as eg character class within the existing data structure, if that is desired.

    so eg, using the example above:

    A[order(factor(A$animal, levels = c("dog", "elephant","cat")) ,factor(A$color, levels = c("green", "blue", "red"))),]
    

    Depends on whether conservation of class is important. This would be a much more typical use case for me personally. HTH

    0 讨论(0)
  • 2020-11-30 07:22

    The levels should be specified explicitly:

    A$animal <- factor(A$animal, levels = c("dog", "elephant","cat"))
    A$color <- factor(A$color, levels = c("green", "blue", "red"))
    

    Then you order by the 2 columns simultaneously:

    A[order(A$animal,A$color),]
    
    # animal color
    # 6      dog green
    # 4      dog  blue
    # 5      dog   red
    # 9 elephant green
    # 7 elephant  blue
    # 8 elephant   red
    # 3      cat green
    # 1      cat  blue
    # 2      cat   red
    
    0 讨论(0)
  • 2020-11-30 07:23

    You can also use match - you do not alter column class neither do a factor transformation.

    animalOrder = c("dog", "elephant","cat")
    colorOrder  = c("green", "blue", "red")
    A[ order(match(A$animal, animalOrder), match(A$color, colorOrder)), ]
    
    animal color
    6      dog green
    4      dog  blue
    5      dog   red
    9 elephant green
    7 elephant  blue
    8 elephant   red
    3      cat green
    1      cat  blue
    2      cat   red
    
    0 讨论(0)
提交回复
热议问题