自定义排序(非字母顺序) [英] Custom sorting (non-alphabetical)
本文介绍了自定义排序(非字母顺序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似于以下内容的分类数据集:
I have a categorical data set that looks similar to:
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 < cat
,然后将颜色分类为green < blue < red
.所以最终看起来像
I want to order it so that 'animal' is sorted as dog < elephant < cat
, and then the color is sorted green < blue < red
. So in the end it would look like
# 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
推荐答案
级别应明确指定:
A$animal <- factor(A$animal, levels = c("dog", "elephant","cat"))
A$color <- factor(A$color, levels = c("green", "blue", "red"))
然后您同时按2列进行订购:
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
这篇关于自定义排序(非字母顺序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文