Re-ordering factor levels in data frame [duplicate]
Asked Answered
P

1

95

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

Probity answered 24/8, 2013 at 0:36 Comment(1)
There is the levels(x) <- value syntax (see ?levels). Is that what you mean?Obsequious
S
180

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
Shaunta answered 24/8, 2013 at 2:17 Comment(4)
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.Probity
also try mydf$task <- ordered(mydf$task levels =c("up", "down", "left", "right", "front", "back")Situla
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 whySpa
@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...Haifa

© 2022 - 2024 — McMap. All rights reserved.