Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

r - 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

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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...