Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify a sort order using a list?

Tags:

sorting

r

Forgive my ignorance, but I'm having trouble with sorting a data frame. I would like to specify an ordered list like c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") when sorting such that the dataframe is sorted in the order of the list.

In this example, I would like to start with

    Day Present Count
    Fri No  164
    Fri Yes 131
    Mon No  142
    Mon Yes 174
    Sat No  39
    Sat Yes 26
    Sun No  44
    Sun Yes 39
    Thu No  191
    Thu Yes 192
    Tue No  184
    Tue Yes 214
    Wed No  343
    Wed Yes 255

And end with

    Day Present Count
    Mon No  142
    Mon Yes 174
    Tue No  184
    Tue Yes 214
    Wed No  343
    Wed Yes 255
    Thu No  191
    Thu Yes 192
    Fri No  164
    Fri Yes 131
    Sat No  39
    Sat Yes 26
    Sun No  44
    Sun Yes 39

I've tried perday[do.call(order, perday[c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")]),] but I get "undefined columns selected". I get the same error if there are 14 entries in the character vector too, so I'm really confused at this point.

Here's the dput:

perday<-structure(list(dayofweek = c("Fri", "Fri", "Mon", "Mon", "Sat", 
"Sat", "Sun", "Sun", "Thu", "Thu", "Tue", "Tue", "Wed", "Wed"
), Attended = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L), .Label = c("No", "Yes"), class = "factor"), 
    nrow = c(164L, 131L, 142L, 174L, 39L, 26L, 44L, 39L, 191L, 
    192L, 184L, 214L, 343L, 255L)), .Names = c("dayofweek", "Attended", 
"nrow"), row.names = c(NA, -14L), class = "data.frame")
like image 412
William Gunn Avatar asked Dec 08 '11 00:12

William Gunn


1 Answers

You can do it "inline" with

perday[order(factor(perday$dayofweek,levels=c(c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")))),]

which gives

   dayofweek Attended nrow
3        Mon       No  142
4        Mon      Yes  174
11       Tue       No  184
12       Tue      Yes  214
13       Wed       No  343
14       Wed      Yes  255
9        Thu       No  191
10       Thu      Yes  192
1        Fri       No  164
2        Fri      Yes  131
5        Sat       No   39
6        Sat      Yes   26
7        Sun       No   44
8        Sun      Yes   39
like image 164
Brian Diggs Avatar answered Sep 29 '22 03:09

Brian Diggs