Re-ordering factor levels in data frame

RDataframeLevelsR Faq

R Problem Overview


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

R Solutions


Solution 1 - R

Assuming your dataframe is mydf:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsiva82kbView Question on Stackoverflow
Solution 1 - RMetricsView Answer on Stackoverflow