首页 > 解决方案 > 基于R中数据框中组内的向量对列值重新排序

问题描述

我有一个数据框如下:

df <- data.frame("QuarterYear" = c("2019 Q1","2019 Q1","2019 Q2","2019 Q2","2019 Q3","2019 Q3","2019 Q3"), "Size" = c("Medium","Small","Large","Medium","Large","Medium","Small"),
                 "percentage" = c(98,2,29,71,13,74,13))

QuarterYear   Size percentage
1  2019 Q1 Medium         98
2  2019 Q1  Small          2
3  2019 Q2  Large         29
4  2019 Q2 Medium         71
5  2019 Q3  Large         13
6  2019 Q3 Medium         74
7  2019 Q3  Small         13

我有一个向量:

size <- c("Small","Medium","Large")

我需要Size根据每个QuarterYear的向量大小来排列列

预期输出如下:

QuarterYear   Size percentage
1    2019 Q1 Small          2
2    2019 Q1 Medium         98
3    2019 Q2 Medium         71
4    2019 Q2 Large          29
5    2019 Q3 Small          13
6    2019 Q3 Medium         74
7    2019 Q3 Large          13

我怎样才能在 R 中实现这一点?

提前致谢!!

标签: rdataframesortingvector

解决方案


这是一个data.table解决方案:

library(data.table)
df = data.table(df)
setorder(df, QuarterYear, -Size)


   QuarterYear   Size percentage
1:     2019 Q1  Small          2
2:     2019 Q1 Medium         98
3:     2019 Q2 Medium         71
4:     2019 Q2  Large         29
5:     2019 Q3  Small         13
6:     2019 Q3 Medium         74
7:     2019 Q3  Large         13

推荐阅读