如何通过 2+ 条件自定义因子变量的订单级别?
How to custom order levels of a factor variable by 2+ conditions?
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
我想按 PCT
中的降序值对 STP_name
因子变量进行排序,但是我希望 ENGLAND
和 MIDLANDS AND EAST OF ENGLAND
的行出现在因子水平的开始,不管它们的 PCT
值如何。
理想情况下寻找 forcats 解决方案,但基础很好。
假设数据集有全部unique
'STP_name',根据[=23=的order
,将其改为factor
,指定levels
] 然后在开头添加两个级别 ("ENGLAND", ""MIDLANDS AND EAST OF ENGLAND") relevel
或 fct_relevel
(from 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")))
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
我想按 PCT
中的降序值对 STP_name
因子变量进行排序,但是我希望 ENGLAND
和 MIDLANDS AND EAST OF ENGLAND
的行出现在因子水平的开始,不管它们的 PCT
值如何。
理想情况下寻找 forcats 解决方案,但基础很好。
假设数据集有全部unique
'STP_name',根据[=23=的order
,将其改为factor
,指定levels
] 然后在开头添加两个级别 ("ENGLAND", ""MIDLANDS AND EAST OF ENGLAND") relevel
或 fct_relevel
(from 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")))