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"?
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.
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 ...
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', ...))
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.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With