自定义排序(非字母顺序)

Custom sorting (non-alphabetical)

提问人:user3379798 提问时间:6/2/2014 最后编辑:Henrikuser3379798 更新时间:6/20/2020 访问量:27715

问:

我有一个分类数据集,看起来类似于:

A < -data.frame(animal = c("cat","cat","cat","dog","dog","dog","elephant","elephant","elephant"),
                color = c(rep(c("blue","red","green"), 3)))

    animal color
1      cat  blue
2      cat   red
3      cat green
4      dog  blue
5      dog   red
6      dog green
7 elephant  blue
8 elephant   red
9 elephant green

我想对它进行排序,以便将“动物”排序为 ,然后对颜色进行排序。所以最后它看起来像dog < elephant < catgreen < blue < red

#     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
R 排序 类别

评论


答:

50赞 agstudy 6/2/2014 #1

应明确指定级别:

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

然后,您同时按 2 列排序:

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
4赞 Pascoe 7/30/2018 #2

另一件值得注意的事情 - 您不必转换类来执行此操作。您可以简单地按变量的因子进行排序。因此,如果需要,在现有数据结构中保留为例如字符类。

因此,例如,使用上面的示例:

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

取决于类守恒是否重要。对我个人来说,这将是一个更典型的用例。HTH型

16赞 xm1 1/9/2019 #3

您还可以使用 - 您不更改列类,也不进行转换。matchfactor

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赞 Ken Osborne 6/20/2020 #4

agstudy的做法类似,我会提出“整洁”的排序方式:

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

然后我们加载或整体,就可以了dplyrtidyverse

arrange(A, animal, color)

或者干脆

A %>% arrange(animal, color)

其中 是 R 中的“管道”运算符,可以使用%>%Ctrl + Shift + m