Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 342
user3379798 Avatar asked Jun 02 '14 13:06

user3379798


People also ask

Can you create your own custom list for sorting in Excel?

Use a custom list to sort or fill in a user-defined order. Excel provides day-of-the-week and month-of-the year built-in lists, but you can also create your own custom list.


Video Answer


1 Answers

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 
like image 92
agstudy Avatar answered Sep 18 '22 22:09

agstudy