Consider the following example
> library(forcats)
> library(dplyr)
>
>
> dataframe <- data_frame(var = c(1,1,1,2,3,4),
+
Suppose your dataframe
is:
dataframe <- data_frame(var = c(1,1,1,2,3,4),var2 = c(10,2,0,15,6,5))
dataframe <- dataframe %>% mutate(myfactor = factor(var))
dataframe$myfactor
[1] 1 1 1 2 3 4
Levels: 1 2 3 4
Now if you want to reorder your factor
, where the order is given by the output of a certain function fun
on a certain vector x
then you can use fct_reorder
in the following way:
dataframe$myfactor= fct_reorder(f = dataframe$myfactor,x = dataframe$var2,fun = mean)
dataframe$myfactor
[1] 1 1 1 2 3 4
Levels: 1 4 3 2
mean
of dataframe$var2
for each factor
will be calculated and sorted in ascending order by default to order the factor.