0

I want to sort a frame by two columns, one is a numerical one and the other a factor column.

Example:

Values  Size       Length
1       "Small"      10
2       "Big"        6
3       "Small"      30
4       "Medium"     22
5       "Very Small" 17
6       "Small"      16

I know how to oder by two columns:

myFrame <- myFrame[order(myFrame$Size,myFrame$Length)]

However, I want to sort the column Size from "Very Small" to "Small" to "Medium" to "Big" and not merely alphabetically.

The result should look like this:

Values   Size           Length
5        "Very Small"   17
1        "Small"        10
3        "Small"        30
6        "Small"        16
4        "Medium"       22
2        "Big"          6

How can I sort the dataset according to the factor column?

musically_ut
  • 34,028
  • 8
  • 94
  • 106
user2974776
  • 301
  • 1
  • 3
  • 8
  • Hi! Welcome to Stackoverflow. I am not the one who down-voted the question, but I would like to give some reasons as to why the question was down-voted. The data you provided was hard to read into R directly and you did not show _enough_ what you had attempted before asking the question. Opinion is divided on _how much_ work you need to show, but as for the first reason, look at this _FAQ_ to provide better data in your later questions: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example I personally think it was a good question, keep asking! :) – musically_ut Nov 10 '13 at 00:23

1 Answers1

1

You can convert the Size column into an ordered factor list:

> d <- read.table(header=T, text='    Values  Size       Length
+     1       "Small"      10
+     2       "Big"        6
+     3       "Small"      30
+     4       "Medium"     22
+     5       "Very Small" 17
+     6       "Small"      16')

> d$Size <- factor(d$Size, levels=c("Very Small", "Small", "Medium", "Big"))
> d[order(d$Size), ]
  Values       Size Length
5      5 Very Small     17
1      1      Small     10
3      3      Small     30
6      6      Small     16
4      4     Medium     22
2      2        Big      6
musically_ut
  • 34,028
  • 8
  • 94
  • 106