Custom sorting (non-alphabetical)

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

提交回复
热议问题