1
   STP_name                                                           PCT
   <fct>                                                            <dbl>
 1 ENGLAND                                                           2.58
 2 MIDLANDS AND EAST OF ENGLAND                                      2.64
 3 LEICESTER, LEICESTERSHIRE AND RUTLAND STP                         2.31
 4 BATH, SWINDON AND WILTSHIRE STP                                   2.94
 5 KENT AND MEDWAY STP                                               2.8 
 6 BUCKINGHAMSHIRE, OXFORDSHIRE AND BERKSHIRE WEST STP               2.73
 7 NORTH CENTRAL LONDON STP                                          1.93
 8 NORTHAMPTONSHIRE STP                                              2.63
 9 SOMERSET STP                                                      3.41
10 SURREY HEARTLANDS STP                                             2.87

我想按STP_name因子变量的降序值对因子变量进行排序PCT,但是我希望 和 的行ENGLAND出现MIDLANDS AND EAST OF ENGLAND在因子水平的开头,而不管它们的PCT值如何。

理想情况下寻找一个 forcats 解决方案,但基础很好。

4

1 回答 1

1

假设数据集都有unique'STP_name',将其更改为基于'PCT'的指定factor,然后在开头添加两个级别(“ENGLAND”,““MIDLANDS AND EAST OF ENGLAND”)或(来自)levelsorderrelevelfct_relevelforcats

library(tidyverse)
library(forcats)
df1 %>%
    mutate(STP_name = fct_relevel(factor(STP_name, levels = STP_name[order(-PCT)]), 
              c("ENGLAND",  "MIDLANDS AND EAST OF ENGLAND")))
于 2018-08-30T13:45:55.277 回答