Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder factor levels by day of the week in R

I have the following data.frame in R:

> daily
        DoW         Duration
1    Friday 14.0000000000000
2    Monday 21.0000000000000
3  Saturday 12.0000000000000
4  Thursday 28.0000000000000
5   Tuesday 12.0000000000000
6 Wednesday 91.0000000000000
7    Sunday 20.0000000000000

I'd like to change the order of the factor levels so that the weeks are in (US) day-of-week order.

It looks like I can do this in a slow, puzzling way with relevel(). But this only takes 1 numeric argument and moves it to the top. So, relevel(daily$DoW, 7), moves Sunday to the top, but the rest remain unordered (which means I need to relevel it in reverse order).

Doable, but there must be a better way, right?

(Time series solution also acceptable.)

like image 205
Mittenchops Avatar asked Apr 25 '12 04:04

Mittenchops


People also ask

How do you reorder the levels of a factor in R?

One way to change the level order is to use factor() on the factor and specify the order directly. In this example, the function ordered() could be used instead of factor() . Another way to change the order is to use relevel() to make a particular level first in the list.

What is the reorder function in R?

reorder is a generic function. The "default" method treats its first argument as a categorical variable, and reorders its levels based on the values of a second variable, usually numeric. Note : Reordering levels, not the values of the factor variable( group in your case).

What does factor function do in R?

The factor function is used to create a factor. The only required argument to factor is a vector of values which will be returned as a vector of factor values. Both numeric and character variables can be made into factors, but a factor's levels will always be character values.


2 Answers

You need to specify the levels in factor and then use order with indexing:

daily$DoW <- factor(daily$DoW, levels= c("Sunday", "Monday", 
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"))

daily[order(daily$DoW), ]
like image 164
Tyler Rinker Avatar answered Sep 20 '22 19:09

Tyler Rinker


Instead of a factor, what you want is an Ordered.Factor.

This line of R code converts your DoW variable to an "Ordered Factor":

daily$DoW <- ordered(daily$DoW, levels=c("Monday", "Tuesday", "Wednesday", "Thursday", 
"Friday", "Saturday", "Sunday"))

Now when you use table, plot or any other functions on Dow it will be the order you specified above.

like image 39
onlyphantom Avatar answered Sep 22 '22 19:09

onlyphantom