根据条件对变量重新排序

Dan*_*ues 2 r dataframe dplyr

我想根据 2018-19 年的生产水平订购我的数据集。因此,首先是公司代码 3 (5000),然后是公司代码 1 (2000),最后是公司代码 2 (1000)。

我有一个这样的数据集:

公司代码 财务年 生产
1 2018-19 2000年
1 2019-20 2500
1 2020-21 3000
1 2018-21 7500
2 2018-19 1000
2 2019-20 1500
2 2020-21 1000
2 2020-21 3500
3 2018-19 5000
3 2019-20 5500
3 2020-21 4000
3 2018-21 14500

我想最终得到:

公司代码 财务年 生产
3 2018-19 5000
3 2019-20 5500
3 2020-21 4000
3 2018-21 14500
1 2018-19 2000年
1 2019-20 2500
1 2020-21 3000
1 2018-21 7500
2 2018-19 1000
2 2019-20 1500
2 2020-21 1000
2 2020-21 3500

我试过:

dataset <- dataset %>% mutate(COMPANY_CODE = reorder(COMPANY_CODE, -production[financial_year=="2018/19"]))
Run Code Online (Sandbox Code Playgroud)

但这不起作用,有人可以帮忙吗?非常感谢

ste*_*fan 5

一种选择是使用辅助“列”,仅保留 2018/19 年的值,并将所有其他值设置为 0,最后FUN=sum在 中使用reorder

library(dplyr)

dataset %>% 
  mutate(company_code = reorder(company_code, -ifelse(financial_year == "2018-19", production, 0), FUN = sum)) |> 
  arrange(company_code)
#>    company_code financial_year production
#> 1             3        2018-19       5000
#> 2             3        2019-20       5500
#> 3             3        2020-21       4000
#> 4             3        2018-21      14500
#> 5             1        2018-19       2000
#> 6             1        2019-20       2500
#> 7             1        2020-21       3000
#> 8             1        2018-21       7500
#> 9             2        2018-19       1000
#> 10            2        2019-20       1500
#> 11            2        2020-21       1000
#> 12            2        2020-21       3500
Run Code Online (Sandbox Code Playgroud)