94

I have a data.frame as shown below:

task    measure
right   m1
left    m2
up      m3
down    m4
front   m5
back    m6
.
.
.

The task column takes only six different values, which are treated as factors, and are ordered by R as: "back", "down", "front", "left", "right", "up".

How ever, I need them ordered as: "up", "down", "left", "right", "front", "back". So that when I use this data in ggplot, the related tasks (such as "up" and "down") are plotted next to each other.

How can change the ordering of the levels of the factor "task"?

Wael
  • 1,640
  • 1
  • 9
  • 20
siva82kb
  • 1,910
  • 4
  • 19
  • 28

1 Answers1

177

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
Metrics
  • 15,172
  • 7
  • 54
  • 83
  • 13
    Thank you. I also found that for just the purpose of changing the ordering for the plot with ggplot2, you can use the function scale_x_discrete and set the limits parameter to the appropriate order required for the factor in the x axis. – siva82kb Aug 24 '13 at 20:34
  • 8
    also try `mydf$task <- ordered(mydf$task levels =c("up", "down", "left", "right", "front", "back")` – user3357059 Nov 28 '17 at 23:30
  • Thanks, also stuck with the same thing, I knew that is related to this through anoter anwser, but playing with factor is always complicated for me, I don't know why – HanniBaL90 Mar 14 '18 at 16:16
  • 3
    @HanniBaL90: Trust me, you're not alone in finding factors somewhat complicated. I've spent a lot of time trying to get factors into the form I require. But issues with factors appears to be rather common... – thandi Dec 13 '19 at 22:50