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解决方案,但基础还可以。
答案 0 :(得分:1)
假定数据集具有所有unique
'STP_name',将其更改为factor
,并根据'PCT'的levels
指定order
,然后将两者相加relevel
或fct_relevel
(从forcats
开始)级别(“英格兰”,“英格兰中部和东部”)
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")))