[r] Re-ordering factor levels in data frame

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"?

This question is related to r dataframe

The answer is


Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))