Custom sorting (non-alphabetical)

后端 未结 4 1531
误落风尘
误落风尘 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: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

提交回复
热议问题