Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-ordering factor levels in data frame [duplicate]

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

like image 820
siva82kb Avatar asked Aug 24 '13 00:08

siva82kb


People also ask

How do you reorder levels of a factor?

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.

How do you reorder ordered factors in R?

Using factor() function to reorder factor levels is the simplest way to reorder the levels of the factors, as here the user needs to call the factor function with the factor level stored and the sequence of the new levels which is needed to replace from the previous factor levels as the functions parameters and this ...

How do I reorder categorical variables in R?

Occasionally you may want to re-order the levels of some factor variable in R. Fortunately this is easy to do using the following syntax: factor_variable <- factor(factor_variable, levels=c('this', 'that', 'those', ...))

What does Fct_reorder do in R?

fct_reorder() is useful for 1d displays where the factor is mapped to position; fct_reorder2() for 2d displays where the factor is mapped to a non-position aesthetic. last2() and first2() are helpers for fct_reorder2() ; last2() finds the last value of y when sorted by x ; first2() finds the first value.


1 Answers

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back")) 
like image 114
Metrics Avatar answered Sep 21 '22 06:09

Metrics