how to reorder a factor in a dataframe with fct_reorder?

前端 未结 2 1111
花落未央
花落未央 2021-01-23 06:07

Consider the following example

> library(forcats)
> library(dplyr)
> 
> 
> dataframe <- data_frame(var = c(1,1,1,2,3,4),
+                              


        
2条回答
  •  孤城傲影
    2021-01-23 06:29

    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.

提交回复
热议问题